In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to insert multiple documents in the collection by using db.collection.insertMany() method.
insertMany() is a mongo shell method, which can insert multiple documents. This method can be used in the multi-document transactions. In this method, you can add documents in the collection with or without _id field. If you add documents without _id field, then mongodb will automatically add _id fields for each documents and assign them with a unique ObjectId. This method by default insert documents in order.
Syntax:
db.collection.insertMany(
[ <Document1>, <Document2>, <Document3> ... ],
{
writeConcern: <Document>,
order: <Boolean>
}
)
Parameters:
Document: It represents the array of the documents that will insert in the collection.
Optional Parameters:
- writeConcern: It is only used when you do not want to use the default write concern,
- order: It specifies whether the mongodb instance performs an ordered or unordered insert, the default value of this parameter is true.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: student

Inserting multiple documents without _id field:
In this example, we are inserting multiple documents in the student collection without _id field using db.collection.insertMany() method.

Inserting multiple documents with field:
In this example, we are inserting multiple documents in the student collection with _id field using db.collection.insertMany() method.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
27 Feb, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...