Before working with collections, ensure you are in the right database. If you haven't created one, switch to a new database using:
use myDatabase
Collections in MongoDB are created automatically when you insert data. However, you can manually create a collection with specific options:
db.createCollection("users")
To add a single document to the users
collection:
db.users.insertOne({ name: "John Doe", age: 30, city: "New York" })
To insert multiple documents:
db.users.insertMany([
{ name: "Alice", age: 25, city: "London" },
{ name: "Bob", age: 28, city: "Toronto" }
])
To fetch all documents from a collection:
db.users.find()
To find specific users, such as those in London:
db.users.find({ city: "London" })
To format the output for better readability:
db.users.find().pretty()
To update a single document:
db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } })
To update multiple documents:
db.users.updateMany({ city: "Toronto" }, { $set: { country: "Canada" } })
To delete a single document:
db.users.deleteOne({ name: "Bob" })
To delete multiple documents:
db.users.deleteMany({ city: "London" })
If you want to remove an entire collection:
db.users.drop()
You’ve now learned how to work with MongoDB collections. Remember:
✅ Collections store multiple documents.
✅ They are created automatically when data is inserted.
✅ You can insert, retrieve, update, and delete documents easily.
Now you can start managing data efficiently in MongoDB! 🚀