You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Reading data from MongoDB is done with the find method. MongoDB's query language uses JSON-style filter objects and a rich set of operators that let you express almost any condition.
find returns a cursor of all documents matching the filter. Without a filter it returns all documents in the collection.
// All documents
db.users.find()
// Documents where age equals 30
db.users.find({ age: 30 })
// Documents where city is "London"
db.users.find({ "address.city": "London" })
findOne returns the first matching document (or null if none match):
db.users.findOne({ email: "alice@example.com" })
MongoDB provides a full set of comparison operators:
db.products.find({ price: { $gt: 50 } }) // greater than
db.products.find({ price: { $gte: 50, $lte: 200 } }) // range
db.products.find({ stock: { $lt: 10 } }) // less than
db.products.find({ status: { $ne: "archived" } }) // not equal
db.products.find({ tag: { $in: ["sale", "new"] } }) // in array
// AND — both conditions must be true
db.users.find({ age: { $gte: 18 }, country: "GB" })
// OR — at least one condition must be true
db.users.find({ $or: [{ age: { $lt: 18 } }, { verified: false }] })
// NOT
db.users.find({ age: { $not: { $gte: 65 } } })
MongoDB makes it easy to query into nested structures using dot notation:
// Documents where the hobbies array contains "cycling"
db.users.find({ hobbies: "cycling" })
// Documents where stats.views is greater than 1000
db.articles.find({ "stats.views": { $gt: 1000 } })
// $elemMatch — all conditions must be true for the same array element
db.orders.find({ items: { $elemMatch: { qty: { $gt: 5 }, price: { $lt: 20 } } } })
The second argument to find is a projection that controls which fields are returned. Use 1 to include and 0 to exclude:
// Return only name and email, exclude _id
db.users.find({}, { name: 1, email: 1, _id: 0 })
Cursors support chained methods for sorting and pagination:
db.products
.find({ inStock: true })
.sort({ price: 1 }) // 1 = ascending, -1 = descending
.skip(20)
.limit(10)
// Case-insensitive search for "mongo" in the title field
db.articles.find({ title: { $regex: /mongo/i } })
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.