Mongo Db Queries

MongoDB Queries Explained

🧠 Mastering MongoDB Queries: Insert, Find, Update, Delete and More

MongoDB is a powerful NoSQL database that uses a flexible, document-based model. In this guide, you’ll learn how to use key MongoDB queries including: Insert, Find, Update, and Delete. This is perfect for beginners and those switching from SQL to NoSQL.

📋 Table of Contents

📥 1. Insert Documents

Use insertOne() or insertMany() to add documents to a collection.

🔸 insertOne()

db.students.insertOne({
  name: "Ravi",
  age: 21,
  course: "Computer Science"
});

🔸 insertMany()

db.students.insertMany([
  { name: "Anita", age: 22, course: "Electronics" },
  { name: "Rahul", age: 20, course: "Mathematics" }
]);

🔍 2. Find Documents

The find() method retrieves documents based on criteria.

🔸 Find All

db.students.find();

🔸 Find by Condition

db.students.find({ age: 21 });

🔸 Pretty Output

db.students.find().pretty();

🛠️ 3. Update Documents

You can modify documents using updateOne(), updateMany(), or replaceOne().

🔸 updateOne()

db.students.updateOne(
  { name: "Ravi" },
  { $set: { course: "Data Science" } }
);

🔸 updateMany()

db.students.updateMany(
  { age: { $gt: 20 } },
  { $set: { status: "Senior" } }
);

🔸 replaceOne()

db.students.replaceOne(
  { name: "Anita" },
  { name: "Anita", age: 23, course: "AI" }
);

🗑️ 4. Delete Documents

🔸 deleteOne()

db.students.deleteOne({ name: "Rahul" });

🔸 deleteMany()

db.students.deleteMany({ age: { $lt: 21 } });

⚙️ 5. Common Query Operators

  • $gt – Greater Than
  • $lt – Less Than
  • $in – In array
  • $and, $or – Logical Operators
db.students.find({
  $or: [
    { course: "Computer Science" },
    { age: { $lt: 22 } }
  ]
});

🧮 6. Sort, Limit & Skip

🔸 sort()

db.students.find().sort({ age: 1 }); // 1 = Asc, -1 = Desc

🔸 limit()

db.students.find().limit(3);

🔸 skip()

db.students.find().skip(2);

🎯 7. Field Projection

To return only selected fields:

db.students.find({}, { name: 1, course: 1, _id: 0 });

✅ 8. Conclusion

MongoDB provides a clean and powerful way to manage data using its intuitive query syntax. Whether you are inserting, reading, updating, or deleting data – MongoDB helps you work with documents efficiently.

Practice these queries using MongoDB Atlas or locally on your system. The more you experiment, the more confident you'll become!

Post a Comment

0 Comments

Me