如何在 MongoDB 中正确使用 save()?
使用 db.collection.save() 更新现有文档或者根据其文档参数插入新文档。我们创建一个包含文档的集合 -
> db.demo481.save({"FirstName":"Chris","LastName":"Brown"}); WriteResult({ "nInserted" : 1 }) > db.demo481.save({"FirstName":"David","LastName":"Miller"}); WriteResult({ "nInserted" : 1 }) > db.demo481.save({"FirstName":"John","LastName":"Doe"}); WriteResult({ "nInserted" : 1 }) > db.demo481.save({"FirstName":"John","LastName":"Smith"}); WriteResult({ "nInserted" : 1 })
借助 find() 方法显示集合中的所有文档 -
> db.demo481.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e82db39b0f3fa88e227909c"), "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : ObjectId("5e82db45b0f3fa88e227909d"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e82db4db0f3fa88e227909e"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5e82db52b0f3fa88e227909f"), "FirstName" : "John", "LastName" : "Smith" }
广告