DEV Community

Full Stack Hacker
Full Stack Hacker

Posted on • Edited on

1 1

Adding data to a MongoDB database (part 2)

The insertMany() allows you to insert multiple documents into a collection. Here is the syntax of the insertMany() method:

 db.collection.insertMany(
   [document1, document2, ...],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

The insertMany() method returns a document that contains:

  • The acknowledged key sets to true if operation executed with a write concern or false if the write concern was disabled.
  • An array of _id values of successfully inserted documents.

MongoDB insertMany() method

First, launch mongo shell from the Terminal on macOS and Linux or Command Prompt on Windows and connect to the bookdb database on the local MongoDB server: mongosh bookdb

Using MongoDB insertMany() method to insert multiple documents without specifying _id fields

db.books.insertMany([
   { title:  "NoSQL Distilled", isbn: "0-4696-7030-4"},
   { title:  "NoSQL in 7 Days", isbn: "0-4086-6859-8"},
   { title:  "NoSQL Database", isbn: "0-2504-6932-4"},
]);

Because we did not specify the _id fields for the documents, MongoDB added the _id field with unique ObjectId to each document.

To retrieve the inserted documents, you use the find() method like this: db.books.find()

Using MongoDB insertMany() method to insert multiple documents with _id fields

db.books.insertMany([
   { _id: 3, title:  "SQL Basics", isbn: "0-7925-6962-8"},
   { _id: 2, title:  "SQL Advanced", isbn: "0-1184-7778-1"}
]);

The following statement attempts to insert documents whose _id value already exist:

db.books.insertMany([
   { _id: 4, title:  "SQL Performance Tuning", isbn: "0-6799-2974-6"},
   { _id: 3, title:  "SQL Index", isbn: "0-5097-1723-3"}
]);

Unordered insert example

The following example uses the insertMany() method to perform an unordered insert:

db.books.insertMany(
   [{ _id: 3, title:  "SQL Performance Tuning", isbn: "0-6799-2974-6"},
   { _id: 3, title:  "SQL Trees", isbn: "0-6998-1556-8"},
   { _id: 4, title:  "SQL Graph", isbn: "0-6426-4996-0"},
   { _id: 5, title:  "NoSQL Pros", isbn: "0-9602-9886-X"},
   { _id: 6, title:  "NoSQL Pros", isbn: "0-9602-9886-X"}], 
   { ordered: false }
);

In this example, the _id: 3 and _id: 4 is duplicated, MongoDB threw an error.

Since this example used the unordered insert, the operation continued to insert the documents with _id 5 and _id 6 into the books collection.

db.books.insertMany(
   [{ _id: 3, title:  "SQL Performance Tuning", isbn: "0-6799-2974-6"},
   { _id: 3, title:  "SQL Trees", isbn: "0-6998-1556-8"},
   { _id: 4, title:  "SQL Graph", isbn: "0-6426-4996-0"},
   { _id: 7, title:  "NoSQL Pros", isbn: "0-9602-9886-X"}], 
   { ordered: true }
);

The above example uses ordered: true, the insert operation will stop if an error is encountered

db.books.insertMany(
...    [{ _id: 3, title:  "SQL Performance Tuning", isbn: "0-6799-2974-6"},
...    { _id: 3, title:  "SQL Trees", isbn: "0-6998-1556-8"},
...    { _id: 4, title:  "SQL Graph", isbn: "0-6426-4996-0"},
...    { _id: 7, title:  "NoSQL Pros", isbn: "0-9602-9886-X"}], 
...    { ordered: true }
... );
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: bookdb.books index: _id_ dup key: { _id: 3 }
Result: BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [
      WriteError {
        err: {
          index: 0,
          code: 11000,
          errmsg: 'E11000 duplicate key error collection: bookdb.books index: _id_ dup key: { _id: 3 }',
          errInfo: undefined,
          op: {
            _id: 3,
            title: 'SQL Performance Tuning',
            isbn: '0-6799-2974-6'
          }
        }
      }
    ],
    writeConcernErrors: [],
    insertedIds: [
      { index: 0, _id: 3 },
      { index: 1, _id: 3 },
      { index: 2, _id: 4 },
      { index: 3, _id: 7 }
    ],
    nInserted: 0,
    nUpserted: 0,
    nMatched: 0,
    nModified: 0,
    nRemoved: 0,
    upserted: []
  }
}

Top comments (0)

Retry later
Retry later