How does MongoDB handle the insertion of multiple documents at once?

QuestionsQuestions8 SkillsProYour First MongoDB LabSep, 06 2025
0157

MongoDB handles the insertion of multiple documents at once using the insertMany method. This method allows you to insert an array of documents in a single operation, which is efficient for adding large amounts of data.

Here’s an example of how to use insertMany:

db.collectionName.insertMany([
  { field1: "value1", field2: "value2" },
  { field1: "value3", field2: "value4" }
])

In this example, replace collectionName with the name of your collection. The documents to be inserted are enclosed in square brackets [ ], indicating that multiple documents are being added.

After executing the command, you will receive a response indicating the operation's success, along with the IDs of the inserted documents:

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("..."),
    '1': ObjectId("...")
  }
}

This method is particularly useful when you have a lot of data to insert, as it reduces the number of operations needed compared to inserting each document individually.

0 Comments

no data
Be the first to share your comment!