mongodb - insert()、insertOne() 和 insertMany() 方法有什么区别?

标签 mongodb nosql

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 , findOneAndUpdatefindOneAndReplace .见 Write Operations Overview .

关于mongodb - insert()、insertOne() 和 insertMany() 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36792649/

相关文章:

javascript - 有没有办法可以将 mongodb 集合作为有序列表发送到 ejs 文件?

mysql - 我如何从关系数据库迁移,我是否需要这样做?

aerospike - 无法连接到本地主机上的 Aerospike

google-cloud-platform - 抛开价格不谈,为什么选择 Google Cloud Bigtable 而不是 Google Cloud Datastore?

C# MongoDB 没有序列化 System.Security.Claims.Claim

javascript - Mongoose + lodash 扩展错误地复制对象数组

mongodb - 设计 mongodb 模式使用嵌入还是引用?

views - CouchDB View 复制

.net - 在RavenDB中更改 “schema”

mongodb - 在同一数据库中复制集合的最快方法是什么?