Inserting Documents

Detailed explanation of inserting single and multiple documents into a collection with various data types.


Inserting Multiple Documents in MongoDB with `insertMany()`

Introduction

This document explains how to insert multiple documents into a MongoDB collection efficiently using the insertMany() method. We'll cover the syntax, error handling, and the difference between ordered and unordered inserts.

The insertMany() Method

The insertMany() method allows you to insert an array of documents into a collection in a single operation. This is significantly more efficient than inserting documents individually, as it reduces the overhead of multiple network round trips to the database.

Syntax

 db.collectionName.insertMany(
   [
      { document1 },
      { document2 },
      ...
      { documentN }
   ],
   {
      ordered: true | false,  // Optional:  Defaults to true
      writeConcern: { ... }   // Optional:  Specifies write concern
   }
) 
  • collectionName: The name of the collection where you want to insert the documents.
  • [ { document1 }, { document2 }, ... ]: An array of BSON documents that you want to insert.
  • ordered: (Optional) A boolean value that determines whether the server should insert the documents in the order they appear in the array. Defaults to true.
  • writeConcern: (Optional) Specifies the level of acknowledgment requested from MongoDB for write operations.

Practical Examples

Example 1: Basic Insertion

This example inserts three new documents into a collection named products.

 db.products.insertMany([
   { name: "Laptop", price: 1200, category: "Electronics" },
   { name: "Keyboard", price: 75, category: "Electronics" },
   { name: "Desk", price: 250, category: "Furniture" }
]); 

Example 2: Unordered Insertion

This example inserts three documents, but specifies ordered: false. This means that if one insert fails, the other inserts will still be attempted.

 db.products.insertMany([
   { name: "Mouse", price: 25, category: "Electronics" },
   { name: "Lamp", price: 50, category: "Furniture" },
   { name: "Laptop", price: 1200, category: "Electronics" }  // Duplicate name - let's assume a unique index exists on 'name'
], { ordered: false }); 

Handling Errors

The insertMany() method returns an object containing information about the operation, including any errors that occurred. The structure of the returned object is as follows:

 {
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
} 

Or, if there is an error (and `ordered: true`):

 {
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("..."),
        ObjectId("...")
    ],
    "insertedCount" : 2,
    "deletedCount" : 0,
    "modifiedCount" : 0,
    "upsertedCount" : 0,
    "matchedCount" : 0,
    "writeErrors" : [
      {
        "index" : 2,
        "code" : 11000,
        "keyPattern" : {
          "name" : 1
        },
        "keyValue" : {
          "name" : "Laptop"
        },
        "errmsg" : "E11000 duplicate key error collection: test.products index: name_1 dup key: { name: \"Laptop\" }"
      }
    ]
  } 
  • acknowledged: A boolean indicating whether the operation was acknowledged by the server.
  • insertedIds: An array of ObjectId values for the newly inserted documents. The index in the array corresponds to the index of the document in the input array.
  • insertedCount: The number of documents successfully inserted.
  • writeErrors: An array of error objects, if any errors occurred during the insertion process. This only exists if there were errors. Each error object typically contains the following properties:
    • index: The index of the document in the input array that caused the error.
    • code: A MongoDB error code.
    • message: A descriptive error message.

Example 3: Error Handling with ordered: true (Default)

If you use the default ordered: true, MongoDB will stop inserting documents as soon as it encounters an error. All documents before the erroring document will be inserted, and all documents after will be ignored.

 try {
    db.products.insertMany([
        { name: "Monitor", price: 300, category: "Electronics" },
        { name: "Chair", price: 150, category: "Furniture" },
        { name: "Monitor", price: 300, category: "Electronics" } // Duplicate name - let's assume a unique index exists on 'name'
    ]);
} catch (e) {
    print(e);
} 

In this example, if there is a unique index on the name field and the third document violates this index, the insert operation will stop at the third document. Only the first two documents ("Monitor" and "Chair") will be inserted.

Example 4: Error Handling with ordered: false

If you set ordered: false, MongoDB will attempt to insert all documents in the array, even if some of them result in errors. This is useful when you want to maximize the number of successful inserts, even if some documents fail to be inserted.

 try {
    db.products.insertMany([
        { name: "MousePad", price: 15, category: "Electronics" },
        { name: "Table", price: 400, category: "Furniture" },
        { name: "MousePad", price: 15, category: "Electronics" } // Duplicate name - let's assume a unique index exists on 'name'
    ], { ordered: false });
} catch (e) {
    print(e);
} 

In this case, even if the third document violates a unique index, the first two documents ("MousePad" and "Table") will still be inserted. The error will be reported in the writeErrors array of the result object. The order of `insertedIds` and any `writeErrors` is not guaranteed.

Ordered vs. Unordered Inserts: A Deeper Dive

The ordered option controls how MongoDB handles errors during the insert operation. Understanding the difference is crucial for choosing the right approach for your application.

Ordered Inserts (ordered: true - Default)

  • Documents are inserted in the order they appear in the array.
  • If an error occurs during the insertion of one document, the operation halts, and no further documents from the array are inserted.
  • This approach guarantees the order of insertion.
  • Suitable when the order of insertion is important, or when you want to ensure that all documents are inserted or none at all (atomicity at the array level).

Unordered Inserts (ordered: false)

  • MongoDB attempts to insert all documents in the array, regardless of errors.
  • If an error occurs, the operation continues with the remaining documents.
  • The order of insertion is not guaranteed.
  • This approach maximizes the number of successful inserts.
  • Suitable when the order of insertion is not important and you want to insert as many documents as possible, even if some fail. Also often faster.

Choosing between ordered and unordered inserts depends on your application's specific requirements. Consider the importance of insertion order and the tolerance for errors when making your decision.

Conclusion

The insertMany() method provides a powerful and efficient way to insert multiple documents into a MongoDB collection. By understanding the syntax, error handling, and the nuances of ordered vs. unordered inserts, you can effectively manage bulk data insertion in your MongoDB applications.