Example
Suppose the collection contains records in the following format:
{
no:1000,
score:80,
interest:["basketball","football"],
major:"计算机科学与技术",
dep:"计算机学院",
info:
{
name:"Tom",
age:25,
gender:"男"
}
}
Select records based on conditions and specify the return field names. The following aggregation operation first uses $match to select records that match the conditions, and then uses $project to return only the specified field names.
db.sample.employee.aggregate( { $match: { $and: [ { no: { $gt: 1002 } },
{ no: { $lt: 1015 } },
{ dep: "计算机学院" } ] } },
{ $project: { no: 1, "info.name": 1, major: 1 } } )
{
"no": 1003,
"info.name": "Sam",
"major": "计算机软件与理论"
}
{
"no": 1004,
"info.name": "Coll",
"major": "计算机工程"
}
{
"no": 1005,
"info.name": "Jim",
"major": "计算机工程"
}
Select records based on conditions and group records. The following operation first uses $match to select records that match the conditions, then uses $group to group records by field major, and uses $avg to return the average value of the age field of the nested objects in each group.
db.sample.employee.aggregate( { $match: { dep: "计算机学院" } },
{ $group: { _id: "$major", Major: { $first: "$major" },
avg_age: { $avg: "$info.age" } } } )
{
"Major": "计算机工程",
"avg_age": 25
}
{
"Major": "计算机科学与技术",
"avg_age": 22.5
}
{
"Major": "计算机软件与理论",
"avg_age": 26
}
Select records according to conditions, group and sort records, and limit the starting position and number of returned records. The following operations first select the records matching the conditions by $match; then use $group to group by major, and use $avg to return the average value of the age field of the nested objects in each group, the output field name is avg_age; finally, use $sort to The avg_age field value (descending order) and the major field value (descending order) sort the result set, use $skip to determine the starting position of the returned records, and use $limit to limit the number of returned records.
db.sample.employee.aggregate( { $match: { interest: { $exists: 1 } } },
{ $group: { _id: "$major",
avg_age: { $avg: "$info.age" },
major: { $first: "$major" } } },
{ $sort: { avg_age: -1, major: -1 } },
{ $skip: 2 },
{ $limit: 3 } )
{
"avg_age": 25,
"major": "计算机科学与技术"
}
{
"avg_age": 22,
"major": "计算机软件与理论"
}
{
"avg_age": 22,
"major": "物理学"
}
Click on Jushan Database Documentation Center for more information