mongodbHow to filter and aggregate in MongoDB?
MongoDB provides powerful aggregation and filtering capabilities. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. Filtering operations allow documents to be filtered so that only those documents that match the specified criteria are returned.
Example code
db.collection.aggregate([
{
$match: {
age: { $gt: 18 }
}
},
{
$group: {
_id: null,
avgAge: { $avg: "$age" }
}
}
])
Output example
{ "_id" : null, "avgAge" : 25.5 }
Code explanation
$match
: This is a filtering operation that allows documents to be filtered so that only those documents that match the specified criteria are returned. In this example, only documents with an age greater than 18 are returned.$group
: This is an aggregation operation that groups values from multiple documents together. In this example, all documents with an age greater than 18 are grouped together and the average age is calculated.
Helpful links
More of Mongodb
- How to rename a field in MongoDB?
- How to use watch in MongoDB?
- How to update many documents in MongoDB?
- How to use MongoDB query with "or" condition?
- How to use MongoDB queue?
- What is MongoDB default port?
- How to bind IP addresses for MongoDB server?
- How to check the version of MongoDB?
- How to convert MongoDB ObjectId to string?
- How to work with time series data in MongoDB?
See more codes...