MongoDB aggregation
Aggregate in MongoDB is mainly used to process data (such as statistical average, summation, etc.) and return the calculated data result.
aggregate() method
The aggregation method in MongoDB uses aggregate(). Similar to count(*) in sql statement.
The result returned by aggregate() is still a document {}, and the _id attribute must be included in the expression, otherwise an error will be reported.
_id indicates the basis of grouping, and the format of a certain field is'$field'.
grammar
The basic syntax format of the aggregate() method is as follows:
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
pipeline
Pipes are generally used in Unix and Linux to use the output of the current command as the parameter of the next command.
MongoDB's aggregation pipeline transfers MongoDB documents to the next pipeline for processing after processing in one pipeline. Pipeline operations can be repeated.
Commonly used pipeline operators in aggregation framework
- $project: Modify the structure of the input document. Can be used to rename, add or delete fields, and can also be used to create calculation results and nested documents.
- $match: Used to filter data, and only output documents that meet the conditions. $match uses MongoDB's standard query operations.
- $limit: Used to limit the number of documents returned by the MongoDB aggregation pipeline.
- $skip: Skip the specified number of documents in the aggregation pipeline and return the remaining documents.
- $unwind: Split a certain array type field in the document into multiple pieces, each containing one value in the array.
- $group: Group documents in the collection, which can be used for statistical results.
- $sort: Sort the input documents and output them.
- $geoNear: Output ordered documents close to a certain geographic location.
Column operation expression
Process input documents and output. Expressions are stateless and can only be used to calculate documents in the current aggregation pipeline, and cannot process other documents.
grammar
- Expression:'$column name'
Frequently used expressions
- $sum: Calculate the sum, $sum:1 is the same as count means count.
- $avg: Calculate the average value.
- $min: Get the minimum value.
- $max: Get the maximum value.
- $push: Insert values into an array in the result document.
- $first: Obtain the first document data according to the sorting of the resource document.
- $last: Get the last document data according to the sorting of the resource document.
Aggregation operation example
Create collection
First, create the following collection in the database:
db.c1.insertMany([
{name:"tom", age:18, gender:"男"},
{name:"lin", age:18, gender:"男"},
{name:"jenney", age:16, gender:"女"},
{name:"klay", age:20, gender:"男"}
])
Note that the corresponding content of the age attribute is the number 18 instead of the string "18", otherwise the subsequent numerical processing cannot be performed.
View all documents in the collection:
db.c1.find()
$group operation
Group documents by name, age, gender attributes and count the number of documents
db.c1.aggregate([{$group : {_id : "$name", num_tutorial : {$sum : 1}}}])
db.c1.aggregate([{$group : {_id : "$age", num_tutorial : {$sum : 1}}}])
db.c1.aggregate([{$group : {_id : "$gender", num_tutorial : {$sum : 1}}}])
_id If scribbling is equivalent to writing null, all counts
db.c1.aggregate([{$group : {_id : "$lol", num_tutorial : {$sum : 1}}}])
db.c1.aggregate([{$group : {_id : null, num_tutorial : {$sum : 1}}}])
$match operation
Find documents with "age greater than 17, and less than or equal to 20"
db.c1.aggregate( [
{ $match : { age : { $gt : 17, $lte : 20 } } }
]);
Pipeline combination operation
The number of documents with "age greater than 17, less than or equal to 20"
db.c1.aggregate( [
{ $match : { age : { $gt : 17, $lte : 20 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
]);
Count documents with "age greater than 10, less than or equal to 20" by gender
db.c1.aggregate( [
{ $match : { age : { $gt : 10, $lte : 20 } } },
{ $group: { _id: "$gender", count: { $sum: 1 } } }
]);