MongoDB Query Cheat Sheet

Below is a MongoDB query cheat sheet covering common operations and syntax for interacting with MongoDB databases:

Basic Queries

Select All Documents:

db.collection.find()

Select Specific Fields:

db.collection.find({}, { field1: 1, field2: 1 })

Query with Equality:

db.collection.find({ field: "value" })

Query with AND Operator:

db.collection.find({ field1: "value1", field2: "value2" })

Query with OR Operator:

db.collection.find({ $or: [{ field1: "value1" }, { field2: "value2" }] })

Comparison Operators

Greater Than:

db.collection.find({ field: { $gt: value } })

Less Than:

db.collection.find({ field: { $lt: value } })

Greater Than or Equal To:

db.collection.find({ field: { $gte: value } })

Less Than or Equal To:

db.collection.find({ field: { $lte: value } })

Element Operators

Existence Check:

db.collection.find({ field: { $exists: true } })

Array Element Match:

db.collection.find({ arrayField: { $elemMatch: { $gt: 10 } } })

Logical Operators

Logical AND:

db.collection.find({ $and: [{ field1: "value1" }, { field2: "value2" }] })

Logical OR:

db.collection.find({ $or: [{ field1: "value1" }, { field2: "value2" }] })

Logical NOT:

db.collection.find({ field: { $not: { $eq: value } } })

Update Operations

Update Documents Matching a Condition:

db.collection.update({ field: "value" }, { $set: { newField: "newValue" } })

Update Multiple Documents:

db.collection.updateMany({ field: "value" }, { $set: { newField: "newValue" } })

Delete Operations

Delete Documents Matching a Condition:

db.collection.deleteOne({ field: "value" })

Delete Multiple Documents:

db.collection.deleteMany({ field: "value" })

Indexing

Create Index:

db.collection.createIndex({ field: 1 })

List Indexes:

db.collection.getIndexes()

Aggregation

Aggregation Pipeline:

db.collection.aggregate([
  { $match: { field: "value" } },
  { $group: { _id: "$field", count: { $sum: 1 } } }
])

This cheat sheet provides a quick reference for common MongoDB queries. Always refer to the official MongoDB documentation for more detailed information and additional query operators.