mongodb - insert()、insertOne() 和 insertMany() 方法有什

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/

相关文章:

mongodb - 如何修复我的mongodb?

mongodb - 选择 MongoDb/CouchDb/RavenDb - 性能和可扩展性建议

mongodb - 如何使用 mongodb 更新包含在父对象数组中的对象的属性?

mongodb - 在 MongoDb 中按 15 分钟的时间间隔对结果进行分组

java - 为什么 Casbah/Java MongoDB 驱动程序会出现 java.lang.I

mongodb - EventStore 与 MongoDb

mongodb - 如何对 MongoDB 集合中所有文档的键值求和

javascript - Meteor 文档中的消息计数示例如何工作?

node.js - Redis 缓存和 Mongo 的持久性架构

mongodb - 在 MongoDB 中存储 null 与根本不存储 key