insert()、insertOne() 和 insertMany() 方法有什么区别? [英] What's the difference between insert(), insertOne(), and insertMany() method?
问题描述
MongoDB 上的 insert()
、insertOne()
和 insertMany()
方法有什么区别.我应该在什么情况下使用它们?
What's the difference between insert()
, insertOne()
, and insertMany()
methods on MongoDB. In what situation should I use each one?
我阅读了文档,但不清楚何时使用每个文档.
I read the docs, but it's not clear when use each one.
推荐答案
MongoDB 上的 insert()、insertOne() 和 insertMany() 方法有什么区别
What's the difference between insert(), insertOne() and insertMany() methods on MongoDB
db.collection.insert()
如文档中所述,将一个或多个文档插入到集合中并返回单个插入的 WriteResult 对象和 BulkWriteResult 用于批量插入的对象.db.collection.insert()
as mentioned in the documentation inserts a document or documents into a collection and returns a WriteResult object for single inserts and a BulkWriteResult object for bulk inserts.> 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()
如文档中所述,将文档插入集合并返回如下所示的文档:db.collection.insertOne()
as mentioned in the documentation inserts a document into a collection and returns a document which look like this:> var document = db.collection.insertOne({"a": 3}) > document { "acknowledged" : true, "insertedId" : ObjectId("571a218011a82a1d94c02333") }
db.collection.insertMany()
将多个文档插入一个集合并返回一个如下所示的文档:db.collection.insertMany()
inserts multiple documents into a collection and returns a document that looks like this:> 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
.请参阅写入操作概述.The
insert()
method is deprecated in major driver so you should use the the.insertOne()
method whenever you want to insert a single document into your collection and the.insertMany
when you want to insert multiple documents into your collection. Of course this is not mentioned in the documentation but the fact is that nobody really writes an application in the shell. The same thing applies toupdateOne
,updateMany
,deleteOne
,deleteMany
,findOneAndDelete
,findOneAndUpdate
andfindOneAndReplace
. See Write Operations Overview.这篇关于insert()、insertOne() 和 insertMany() 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!