MongoDB offers powerful querying capabilities to retrieve documents from collections:
find()
: Retrieves multiple documents from a collection.
Example: db.users.find({ age: { $gt: 25 } })
findOne()
: Retrieves a single document from a collection.
Example: db.users.findOne({ name: 'John Doe' })
Query operators:
Comparison: $eq
, $gt
, $gte
, $lt
, $lte
, $ne
, $in
, $nin
Example: db.users.find({ age: { $gte: 18, $lte: 30 } })
Logical: $and
, $or
, $not
, $nor
Example: db.users.find({ $or: [{ age: { $lt: 18 } }, { age: { $gt: 60 } }] })
Element: $exists
, $type
Example: db.users.find({ email: { $exists: true } })
Array: $all
, $elemMatch
, $size
Example: db.posts.find({ tags: { $all: ['mongodb', 'database'] } })
Projection: Specify which fields to return in the result documents.
Example: db.users.find({}, { name: 1, email: 1, _id: 0 })
Cursor methods:
sort()
: Sorts the result set. Example: db.users.find().sort({ age: -1 })
limit()
: Limits the number of documents returned. Example: db.users.find().limit(5)
skip()
: Skips a specified number of documents. Example: db.users.find().skip(10)
These methods can be combined for pagination: db.users.find().sort({ age: -1 }).skip(20).limit(10)