Problem Statement
Which method would you use to insert multiple documents at once in MongoDB?
Explanation
The insertMany method is used to insert multiple documents into a collection at once. You pass an array of documents to insertMany, and MongoDB inserts them in a single operation.
This is more efficient than calling insertOne multiple times because it reduces network round trips and allows MongoDB to optimize the insertion process. insertOne is used for single documents, while insertMultiple and bulkInsert are not valid MongoDB methods.
Code Solution
SolutionRead Only
// Insert multiple documents
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
])
// Returns:
{
acknowledged: true,
insertedIds: [ObjectId(), ObjectId(), ObjectId()]
}