Before inserting data, ensure you're in the correct database. If the database doesn't exist, MongoDB will create it automatically when inserting data.
use myDatabase
To insert a single document into a collection, use insertOne(). If the collection doesn't exist, MongoDB creates it automatically.
db.users.insertOne({
name: "John Doe",
age: 30,
city: "New York"
})
✅ MongoDB automatically assigns a unique _id field to each document.
To insert multiple documents at once, use insertMany().
db.users.insertMany([
{ name: "Alice", age: 25, city: "London" },
{ name: "Bob", age: 28, city: "Toronto" },
{ name: "Charlie", age: 32, city: "Sydney" }
])
✅ All documents are stored in the users collection.
To check if the data was inserted correctly, use the find() command:
db.users.find()
For a more readable output:
db.users.find().pretty()
_idYou can define a custom _id field instead of the default one generated by MongoDB.
db.users.insertOne({
_id: 101,
name: "David",
age: 29,
city: "Berlin"
})
✅ Ensure _id values are unique to avoid errors.
_id that already exists, MongoDB will throw an error.insertMany() allows you to use { ordered: false } to continue inserting even if some documents fail.db.users.insertMany([
{ _id: 102, name: "Emma", age: 27, city: "Paris" },
{ _id: 102, name: "Oliver", age: 30, city: "Madrid" }
], { ordered: false })
✅ The second document will fail, but the first will still be inserted.
You’ve now learned how to insert data into MongoDB collections. Here’s a quick recap:
✅ Use insertOne() for inserting a single document.
✅ Use insertMany() for inserting multiple documents.
✅ Verify inserted data using find().
✅ Handle errors with ordered inserts.
Now you're ready to start managing your data efficiently in MongoDB! 🚀