MongoDB上的insert()insertOne()insertMany()方法有什么区别.在什么情况下我应该使用每一个?

我读了这些文件,但不清楚什么时候使用它们.

推荐答案

MongoDB上的insert()、insertOne()和insertMany()方法有什么区别

  • db.collection.insert()如文档中所述,将一份或多份文档插入集合并返回

    > 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")
            ]
    }
    

在什么情况下我应该使用每一个?

在主驱动程序中,insert()方法已被弃用,因此您应该使用

Mongodb相关问答推荐

geoLocation或geoNear为坐标和半径使用let变量

在对象mongodb的数组中查找元素

MongoDB DB参考返回null值

避免在 MongoDB 聚合框架中使用 ISODate() 以便管道可以是纯 JSON

MongoDB:从开始日期和结束日期数组中匹配特定日期的聚合查询

Golang:如何判断 collection.Find 是否没有找到任何文件?

MongoDB - 使用许多嵌套对象更新嵌套数组

(MongoDB)在同一管道中结合联合和交集

如何将查询结果(单个文档)存储到变量中?

使用 nodejs/mongoose 部分更新子文档

Mongo DB中的Upserting和Id问题

为多个日期范围聚合 $group

MongoDB:多个 $elemMatch

无法连接到远程 mongodb 服务器

使用 MongoDB 进行嵌套分组

如何确保基于特定字段的数组中的唯一项 - mongoDB?

MongoDb 数据库与集合

多次使用位置 `$` 运算符来更新嵌套数组

在 mongodb 集合中查找最旧/最新的帖子

MissingSchemaError:Schema hasn't been registered for model