Introduction
We use insert with arrays to add many items to a database at once. It saves time and keeps data organized.
Jump into concepts and practice - no test required
We use insert with arrays to add many items to a database at once. It saves time and keeps data organized.
db.collection.insertMany([
{ document1 },
{ document2 },
...
])db.fruits.insertMany([
{ name: "Apple", color: "Red" },
{ name: "Banana", color: "Yellow" }
])db.students.insertMany([])
db.books.insertMany([
{ title: "Book One", author: "Author A" }
])This program creates a 'students' collection, inserts three student records at once, prints their new IDs, and then prints all students in the collection.
use school db.students.drop() // Insert multiple student records const result = db.students.insertMany([ { name: "Alice", age: 14, grade: 9 }, { name: "Bob", age: 15, grade: 10 }, { name: "Charlie", age: 14, grade: 9 } ]) // Show inserted IDs printjson(result.insertedIds) // Show all students const allStudents = db.students.find().toArray() printjson(allStudents)
insertMany() is faster than inserting one document at a time.
By default (ordered: true), if one document fails, preceding documents are inserted but subsequent ones are not.
Remember to check the result to confirm all documents were added.
Use insertMany() to add multiple documents to a MongoDB collection at once.
Documents are passed as an array inside insertMany().
This method helps save time and keeps data organized.
insertMany() method do in MongoDB?insertMany() method is used to add several documents to a MongoDB collection in one operation.deleteMany(), updateMany(), and find().insertMany()?db.collection.insertMany([{name: 'Alice'}, {name: 'Bob'}]) correctly passes an array of objects. The other options pass multiple arguments or wrong types, causing syntax errors.db.users.insertMany([
{name: 'John', age: 25},
{name: 'Jane', age: 30}
])
const count = db.users.countDocuments()insertMany() call inserts two documents into the users collection.countDocuments() method returns the total number of documents in the collection, which is 2 after insertion.db.products.insertMany(
{name: 'Pen', price: 1.5},
{name: 'Pencil', price: 0.5}
)insertMany([{...}, {...}]).const users = [
{name: 'Anna', age: 17},
{name: 'Ben', age: 20},
{name: 'Cara', age: 22}
];
// Which code inserts only users older than 18?filter() to keep only users with age greater than 18.