MongoDB 上的 insert()
、insertOne()
和 insertMany()
方法有什么区别。我应该在什么情况下使用它们?
我阅读了文档,但不清楚何时使用每个文档。
最佳答案
What's the difference between insert(), insertOne() and insertMany() methods on MongoDB
db.collection.insert()
如文档中所述,将一个或多个文档插入集合并返回 一个 WriteResult单个插入的对象和 BulkWriteResult用于批量插入的对象。> var d = db.collection.insert({"b": 3}) > d WriteResult({ "nInserted" : 1 }) > var d2 = db.collection.insert([{"b": 3}, {'c': 4}]) > d2 BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
db.collection.insertOne()
如文档中所述,将文档插入集合并返回如下所示的文档:> var document = db.collection.insertOne({"a": 3}) > document { "acknowledged" : true, "insertedId" : ObjectId("571a218011a82a1d94c02333") }
db.collection.insertMany()
将多个文档插入一个集合并返回一个如下所示的文档:> var res = db.collection.insertMany([{"b": 3}, {'c': 4}]) > res { "acknowledged" : true, "insertedIds" : [ ObjectId("571a22a911a82a1d94c02337"), ObjectId("571a22a911a82a1d94c02338") ] }
In what situation should I use each one?
insert()
方法在主要驱动程序中已弃用,因此您应该使用
.insertOne()
方法可以在您想要将单个文档插入您的集合时使用,而 .insertMany
当您想要将多个文档插入您的集合时使用。当然,文档中没有提到这一点,但事实是没有人真正在 shell 中编写应用程序。同样的事情适用于 updateOne
, updateMany
, deleteOne
, deleteMany
, findOneAndDelete
, findOneAndUpdate
和 findOneAndReplace
.见 Write Operations Overview .
关于mongodb - insert()、insertOne() 和 insertMany() 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36792649/