What's the difference between insert(), insertOne(), and insertMany() method?

前端 未结 4 1378
天命终不由人
天命终不由人 2020-12-03 00:15

What\'s the difference between insert(), insertOne(), and insertMany() methods on MongoDB. In what situation should I use each one?

4条回答
  •  臣服心动
    2020-12-03 00:52

    1. db.collection.insert():

      It allows you to insert One or more documents in the collection. Syntax:

      • Single insert: db.collection.insert({});
      • Multiple insert:

        db.collection.insert([ , , ... ]);

      Returns a WriteResult object: WriteResult({ "nInserted" : 1 });

    2. db.collection.insertOne():

      It allows you to insert exactly 1 document in the collection. Its syntax is the same as that of single insert in insert().

      Returns the following document:

      {
         "acknowledged" : true,
         "insertedId" : ObjectId("56fc40f9d735c28df206d078")
      }
      
    3. db.collection.insertMany():

      It allows you to insert an array of documents in the collection. Syntax:

      db.collection.insertMany(
          { [  , , ... ] });
      

      Returns the following document:

      {
         "acknowledged" : true,
         "insertedIds" : [
            ObjectId("562a94d381cb9f1cd6eb0e1a"),
            ObjectId("562a94d381cb9f1cd6eb0e1b"),
            ObjectId("562a94d381cb9f1cd6eb0e1c")
         ]
      }
      

    All three of these also allow you to define a custom writeConcern and also create a collection if it doesn't exist.

提交回复
热议问题