What are the 4 basic operations in MongoDB?
MongoDB, being a NoSQL database, revolves around collections and documents instead of tables and rows. Its four basic operations, also known as CRUD operations, are:
1. Create
This operation is used to add new documents to a collection. It corresponds to inserting data.
- Command:
insertOne()
orinsertMany()
- Example:
db.users.insertOne({ name: "Alice", age: 30 }); db.users.insertMany([{ name: "Bob", age: 25 }, { name: "Charlie", age: 35 }]);
2. Read
This operation retrieves documents from a collection. You can use queries to filter and find specific data.
- Command:
find()
orfindOne()
- Example:
db.users.find({ age: { $gt: 25 } }); // Find users older than 25 db.users.findOne({ name: "Alice" }); // Find the first user named Alice
3. Update
This operation modifies existing documents in a collection. You can update one or multiple documents.
- Command:
updateOne()
,updateMany()
, orreplaceOne()
- Example:
db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } }); // Update Alice's age to 31 db.users.updateMany({}, { $inc: { age: 1 } }); // Increment age of all users by 1
4. Delete
This operation removes documents from a collection. You can delete one or multiple documents.
- Command:
deleteOne()
ordeleteMany()
- Example:
db.users.deleteOne({ name: "Alice" }); // Delete the first document named Alice db.users.deleteMany({ age: { $lt: 30 } }); // Delete all users younger than 30
Learn MongoDB Efficiently
If you're preparing for interviews or want a deep dive into MongoDB and database concepts, consider these resources:
- Grokking SQL for Tech Interviews: Helps bridge SQL and MongoDB knowledge. Check it out here
- Relational Database Design and Modeling for Software Engineers: Enhances your database design skills, applicable to MongoDB. Explore the course
Understanding these operations is essential for mastering MongoDB's capabilities in application development and data management.
GET YOUR FREE
Coding Questions Catalog