In MongoDB, the insertMany
operation is used to insert multiple documents into a collection in one go. This method is essential for bulk inserting records into MongoDB collections.
db.collection.insertMany(documents, options)
The insertMany
method takes an array of documents
to specify the documents to be inserted and an optional options
parameter to customize the insertion.
Let's look at some examples of how to use the insertMany
method in the programGuru
collection in MongoDB:
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
This command inserts multiple documents with the fields name
, age
, and email
into the programGuru
collection.
Let's go through a complete example that includes switching to a database, creating a collection, and inserting multiple documents.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
This step involves using the insertMany
method to insert documents into the programGuru
collection.
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
We insert multiple documents with the fields name
, age
, and email
into the programGuru
collection.
The MongoDB insertMany
operation is crucial for bulk inserting records into collections. Understanding how to use this method allows you to efficiently add and manage large amounts of data within MongoDB collections.