
Query Api in MongoDB
Query API in MongoDB
The MongoDB Query API is used to perform operations on documents stored in a MongoDB collection. It allows you to filter, sort, and manipulate data based on different criteria using queries. MongoDB queries are written in BSON format (Binary JSON), which is similar to JSON but can store more complex types.
Key Query Methods in MongoDB
The MongoDB Query API provides various methods to retrieve, update, and delete documents. These queries are executed using the MongoDB MongoClient object when interacting with a MongoDB database from a Node.js application, or using the Mongo Shell directly.
1. find()
– Retrieve Documents
The find()
method is used to query documents in a collection. It returns a cursor which can be used to iterate through the results.
Syntax:
db.collection.find(query, projection)
- query: A query filter to specify the criteria to match documents.
- projection: (optional) A field specification to limit the fields that are returned.
Example: Basic find
query
// Find all documents in the 'users' collectiondb.users.find({})// Find a document with a specific fielddb.users.find({ name: "Alice" })
Example: Using Projection
// Return only the 'name' and 'age' fields from all documentsdb.users.find({}, { name: 1, age: 1 })
- Note: The
{ name: 1, age: 1 }
projection means that only thename
andage
fields are included in the result.
2. findOne()
– Retrieve a Single Document
The findOne()
method retrieves the first document that matches the query. It is often used when you expect to find only one document.
- Syntax:
db.collection.findOne(query, projection)
Example: findOne
to find a user by name
// Find one document with the name 'Alice'db.users.findOne({ name: "Alice" })
3. countDocuments()
– Count Documents
The countDocuments()
method returns the number of documents that match a query filter.
- Syntax:
db.collection.countDocuments(query)
Example: Count documents in the collection
// Count the number of users with age greater than 30db.users.countDocuments({ age: { $gt: 30 } })
4. distinct()
– Get Distinct Values
The distinct()
method returns an array of distinct values for a given field across all documents that match the query.
- Syntax:
db.collection.distinct(field, query)
Example: Get distinct values of the age
field
// Get all distinct ages in the 'users' collectiondb.users.distinct("age")
5. sort()
– Sort Query Results
The sort()
method is used to sort the results of a query by a specific field. You can specify the order of the sort: ascending (1) or descending (-1).
- Syntax:
db.collection.find().sort({ field: 1 }) // Ascending orderdb.collection.find().sort({ field: -1 }) // Descending order
Example: Sorting documents
// Sort users by age in ascending orderdb.users.find().sort({ age: 1 })// Sort users by age in descending orderdb.users.find().sort({ age: -1 })
6. limit()
– Limit Number of Results
The limit()
method is used to limit the number of documents returned by a query.
- Syntax:
db.collection.find().limit(n)
Example: Limit the number of results
// Return only 3 usersdb.users.find().limit(3)
7. skip()
– Skip Documents
The skip()
method is used to skip a specified number of documents. It is often used in conjunction with limit()
for pagination.
- Syntax:
db.collection.find().skip(n)
Example: Skip a number of documents
// Skip the first 5 users and return the next 3 usersdb.users.find().skip(5).limit(3)
8. Query Operators in MongoDB
MongoDB provides several query operators to filter documents based on different criteria. These operators can be used in the query object to match specific fields and values.
Common Query Operators:
Equality:
{ field: value }
: Matches documents wherefield
equalsvalue
.- Example:
{ age: 25 }
matches documents whereage
is exactly 25.
Comparison:
$gt
: Greater than.$gte
: Greater than or equal to.$lt
: Less than.$lte
: Less than or equal to.$ne
: Not equal to.- Example:
{ age: { $gt: 30 } }
matches documents whereage
is greater than 30.
Logical:
$and
: Matches documents that satisfy all of the specified conditions.$or
: Matches documents that satisfy at least one of the specified conditions.$nor
: Matches documents that fail all the specified conditions.$not
: Negates a condition.- Example:
{ $or: [{ age: { $lt: 20 } }, { name: "Alice" }] }
matches documents whereage
is less than 20 orname
is "Alice".
Array:
$in
: Matches any value in an array.$nin
: Matches any value not in an array.- Example:
{ age: { $in: [25, 30, 35] } }
matches documents whereage
is one of 25, 30, or 35.
Element:
$exists
: Matches documents where the field exists or does not exist.- Example:
{ name: { $exists: true } }
matches documents wherename
field exists.
Regular Expressions:
$regex
: Matches documents where the field value matches a regular expression pattern.- Example:
{ name: { $regex: /^A/ } }
matches documents where thename
field starts with the letter "A".
9. Update Queries
While find()
and findOne()
are used for querying, MongoDB also provides update methods to modify documents.
updateOne()
: Update a single document.updateMany()
: Update multiple documents.replaceOne()
: Replace an entire document.
Example of updating a document:
// Update a user's age by namedb.users.updateOne( { name: "Alice" }, { $set: { age: 31 } })
10. Example Queries in MongoDB
Example 1: Find all users who are older than 25 and sort by age in descending order
db.users.find({ age: { $gt: 25 } }).sort({ age: -1 })
Example 2: Find users whose name starts with 'A'
db.users.find({ name: { $regex: /^A/ } })
Example 3: Count the number of users with a specific age
db.users.countDocuments({ age: 30 })
Example 4: Find users who are either under 20 years old or have the name 'Alice'
db.users.find({ $or: [{ age: { $lt: 20 } }, { name: "Alice" }] })
Conclusion
The MongoDB Query API provides a powerful and flexible way to interact with documents in a MongoDB database. Using the query methods like find()
, findOne()
, countDocuments()
, and others, you can easily retrieve, filter, and manipulate data according to your needs. Additionally, the API supports a wide range of query operators to perform complex queries, including comparison operators, logical operators, array operators, and regular expressions.
MongoDB’s query capabilities are designed to handle unstructured or semi-structured data while providing robust functionality for searching and filtering, making it ideal for modern applications.