MongoDB aggregation query
MongoDB supports multiple aggregation query operations, and the following are some commonly used aggregation query operations:
1. $match: Filter documents based on specified criteria.
Example:
db.collection.aggregate([
{ $match: { age: { $gte: 18 } } }
])
This example will select all documents with age fields greater than or equal to 18 from the collection.
2. $group: Group according to the specified fields and perform aggregation operations.
Example:
db.collection.aggregate([
{ $group: { _id: "$category", count: { $sum: 1 } } }
])
This example will group based on the category field and calculate the number of documents under each category.
3. $sort: Sort the document according to the specified fields.
Example:
db.collection.aggregate([
{ $sort: { age: -1 } }
])
This example will sort in descending order according to the age field.
4. $project: Project the document and only return the specified fields.
Example:
db.collection.aggregate([
{ $project: { name: 1, age: 1 } }
])
This example only returns the name and age fields.
5. $limit: Limit the number of documents returned.
Example:
db.collection.aggregate([
{ $limit: 10 }
])
This example only returns the first 10 documents.
6. $skip: Skip the specified number of documents.
Example:
db.collection.aggregate([
{ $skip: 5 }
])
This example skips the first 5 documents.
7. $unwrind: Splits a document containing an array into multiple documents.
Example:
db.collection.aggregate([
{ $unwind: "$tags" }
])
This example splits a document containing a tag array into multiple documents, each containing only one tag.
The above are just some commonly used examples of aggregation query operations. MongoDB also supports other more complex aggregation query operations, such as $lookup, $project, $group, etc., which can be selected and combined according to actual needs.