insert()
、insertOne()
和insertMany()
是MongoDB上的三种插入数据方法。它们有什么区别?在什么情况下应该使用每个方法呢?
我已经阅读了文档,但还不清楚何时该使用每个方法。
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()
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()
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")
]
}
insert()
方法已经在主要驱动程序中被弃用,因此您应该在想要将单个文档插入到集合中时使用 .insertOne()
方法,而在想要将多个文档插入到集合中时使用 .insertMany()
方法。当然,这在文档中没有提到,但事实上没有人真正在 shell 中编写应用程序。同样的事情也适用于 updateOne
, updateMany
, deleteOne
, deleteMany
, findOneAndDelete
, findOneAndUpdate
和 findOneAndReplace
。请参见写操作概述。db.collection.insert()
:
它允许您在集合中插入一个或多个文档。语法:
db.collection.insert({<document>});
多个插入:
db.collection.insert([ , , ... ]);
返回一个WriteResult
对象: WriteResult({ "nInserted" : 1 });
db.collection.insertOne()
:
它允许您在集合中插入正好1个文档。其语法与insert()
中的单个插入相同。
返回以下文档:
{
"acknowledged" : true,
"insertedId" : ObjectId("56fc40f9d735c28df206d078")
}
db.collection.insertMany()
:
它允许你在集合中插入一个文档数组。语法:
db.collection.insertMany(
{ [ <document 1> , <document 2>, ... ] });
返回以下文件:{
"acknowledged" : true,
"insertedIds" : [
ObjectId("562a94d381cb9f1cd6eb0e1a"),
ObjectId("562a94d381cb9f1cd6eb0e1b"),
ObjectId("562a94d381cb9f1cd6eb0e1c")
]
}
这三种方法都允许您定义自定义的writeConcern
,并且如果它不存在,还可以创建一个集合。
在错误处理方面,还存在差异,请查看此处。对于成功和错误情况下的插入命令,都会返回一个文档。但是,insertOne和insertMany命令会抛出异常。与评估返回的文档以确定错误相比,异常在代码中更容易处理。这可能就是它们在驱动程序中被弃用的原因,正如sstyvane的答案中所提到的。