0
0
MongoDBquery~5 mins

Insert with arrays in MongoDB

Choose your learning style9 modes available
Introduction

We use insert with arrays to add many items to a database at once. It saves time and keeps data organized.

When you want to add a list of new users to your app all at once.
When you have many product details to add to your store database.
When you collect multiple survey answers and want to save them together.
When you want to quickly add many blog posts or articles.
When you receive a batch of sensor readings and want to store them.
Syntax
MongoDB
db.collection.insertMany([
  { document1 },
  { document2 },
  ...
])
Use insertMany() to add multiple documents (items) at once.
Each document is inside curly braces { } and separated by commas.
Examples
Inserts two fruit documents into the fruits collection.
MongoDB
db.fruits.insertMany([
  { name: "Apple", color: "Red" },
  { name: "Banana", color: "Yellow" }
])
Inserts an empty array, which means no documents are added.
MongoDB
db.students.insertMany([])
Inserts one book document using insertMany with a single item array.
MongoDB
db.books.insertMany([
  { title: "Book One", author: "Author A" }
])
Sample Program

This program creates a 'students' collection, inserts three student records at once, prints their new IDs, and then prints all students in the collection.

MongoDB
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)
OutputSuccess
Important Notes

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.

Summary

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.