Lessons
MongoDB Introduction
MongoDB Installation & Setup
MongoDB Create Database & Collections
MongoDB Query API
The MongoDB Query API is the set of commands and operators used to interact with documents in MongoDB collections?like searching, filtering, updating, inserting, and deleting documents. It?s typically used with the MongoDB shell, drivers (Node.js, Python, PHP, etc.), or tools like Compass.
Here?s a quick reference to the most common MongoDB Query API operations, using MongoDB's JavaScript shell syntax (db.collection.):
1. Find Documents
db.users.find({ age: { $gte: 18 } })
Returns all users aged 18 or older.
Use
.findOne()to get just one document.
2. Query Operators
- Comparison:
$eq,$ne,$gt,$gte,$lt,$lte,$in,$nin- Logical:
$and,$or,$not,$nor- Element:
$exists,$type- Evaluation:
$regex,$expr,$mod,$text
3. Insert Documents
db.users.insertOne({ name: "Alice", age: 30 })
db.users.insertMany([{ name: "Bob" }, { name: "Charlie" }])
4. Update Documents
db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
db.users.updateMany({ age: { $lt: 18 } }, { $set: { minor: true } })
5. Delete Documents
db.users.deleteOne({ name: "Alice" })
db.users.deleteMany({ age: { $lt: 18 } })
6. Aggregation
db.orders.aggregate([
{ $match: { status: "complete" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } }
])
7. Count / Sort / Limit / Skip
db.users.find({}).sort({ age: -1 }).limit(10).skip(5)
db.users.countDocuments({ age: { $gt: 20 } })
8. Text Search
db.articles.createIndex({ title: "text" })
db.articles.find({ $text: { $search: "mongodb" } })