MongoDB Query API
- The MongoDB Query API provides powerful methods to retrieve, filter, and shape documents from a database using flexible criteria and operators.
- This guide covers essential query patterns and how to use operators, projections, sorting, and pagination for effective data retrieval.
1. Basic Queries
Basic queries search for documents based on direct key-value criteria within a collection.
Example:
db.collection.find({ key: value })
This command fetches all documents from collection
where the field key
matches value
.
2. Comparison Operators
The Query API supports comparison operators to select documents matching conditions.
$eq
: equal to (default, e.g.,{ age: 25 }
)$ne
: not equal to$gt
: greater than$gte
: greater than or equal to$lt
: less than$lte
: less than or equal to
Examples:
db.collection.find({ age: { $gt: 30 } })
db.collection.find({ price: { $lt: 100 } })
These queries fetch all documents where age
is greater than 30 and price
is less than 100, respectively.
3. Logical Operators
Logical operators combine multiple conditions in a single query, allowing for complex data retrieval.
$and
: matches documents that satisfy all specified conditions$or
: matches documents that satisfy at least one specified condition$nor
: excludes documents that match any specified condition$not
: inverts condition
Examples:
db.collection.find({ $and: [{ key1: value1 }, { key2: value2 }] })
db.collection.find({ $or: [{ key1: value1 }, { key2: value2 }] })
The $and
example returns documents satisfying both conditions. The $or
query returns documents matching either.
4. Array Queries
MongoDB seamlessly queries fields containing arrays. You can match specific elements or find documents where arrays include at least one matching value.
Example:
db.collection.find({ tags: "mongodb" })
This returns documents where the tags
array contains the string mongodb
.
- To match arrays with specific elements or with all given values, use operators like
$all
,$elemMatch
, or$size
for advanced array queries.
5. Projection
Projection lets you specify which fields to display in your query results: include (1) or exclude (0) fields as needed.
Example:
db.collection.find({}, { _id: 0, name: 1 })
This returns each document without the _id
field, displaying only the name
field. By default, _id
is always returned unless specifically excluded.
6. Sorting Results
Use the sort()
method to order query results by field.
1
— Ascending-1
— Descending
Example:
db.collection.find().sort({ field: 1 })
This retrieves documents sorted in ascending order by field
. For descending order, use field: -1
.
7. Limit and Skip
paginating large result sets is simple with limit()
and skip()
.
limit(n)
: restricts results ton
documents.skip(n)
: skips the firstn
documents.
Example:
db.collection.find().limit(10).skip(5)
This fetches 10 documents after skipping the first 5.
8. Additional Query Features
- Use
countDocuments()
to get a count of matching documents. - Apply
distinct()
to retrieve unique values for a specific field. - Build compound queries using combinations of logical and comparison operators for flexible searching.
Comments
Post a Comment