Group of aggregation operations
Grammar:
Db.collection.group (
{
Key:{key1:1,key2:1},
cond:{},
Reduce:function (Curr,result) {
},
initial:{},
Finalize:function () {
}
}
)
Key: Group Field
Cond: Query criteria
Reduce: aggregate function
Initial: Initialization
Finalize: Statistics a set of callback functions
#查询每个栏目下的商品数量
Db.goods.group (
{
Key:{cat_id:1},
cond:{},
Reduce:function (Curr,result) {
result.cnt + = 1;
},
initial:{cnt:0}
}
)
#查询每个栏目下价格高于50元的商品数量
Db.goods.group (
{
Key:{cat_id:1},
cond:{shop_price:{$GT: 50}},
Reduce:function (Curr,result) {
result.cnt + = 1;
},
initial:{cnt:0}
}
)
#每个栏目下的商品库存量 sum () operation
Db.goods.group (
{
Key:{cat_id:1},
cond:{},
Reduce:function (Curr,result) {
Result.num + = Curr.goods_number;
},
initial:{num:0}
}
)
#查询每个栏目最贵的商品价格, Max () operation
Db.goods.group (
{
Key:{cat_id:1},
cond:{},
Reduce:function (Curr, result) {
if (Curr.shop_price > Result.max) {
Result.max = Curr.shop_price;
}
},
initial:{max:0}
}
)
#查询每个栏目下商品的平均价格
Db.goods.group (
{
Key:{cat_id:1},
cond:{},
Reduce:function (Curr, result) {
result.cnt + = 1;
Result.sum + = Curr.shop_price;
},
initial:{sum:0,cnt:0},
Finalize:function (Result) {
Result.avg = result.sum/result.cnt;
}
}
)
Simple aggregation using the aggregate aggregation framework
#查询每个栏目下的商品数量
Db.collection.aggregate
(
[
{$group: {_id: "$cat _id", total:{$sum: 1}}
]
);
#查询goods下有多少条商品, select COUNT (*) from goods
Db.collection.aggregate
(
[
{$group: {_id:null,total:{$sum: 1}}}
]
)
#查询每个栏目下 the number of items with a price greater than 50 yuan
Db.collection.aggregate
(
[
{$match: {shop_price:{$gt: 50}}},
{$group: {_id: "$cat _id", total:{$sum: 1}}
]
)
#查询每个栏目下 the number of items with a price greater than 50 yuan
#并筛选出 "Number of items satisfying the condition" is greater than or equal to 3 columns
Db.collection.aggregate
(
[
{$match: {shop_price:{$gt: 50}}},
{$group: {_id: "$cat _id", total:{$sum: 1}},
{$match: {total:{$gte: 3}}}
]
)
#查询每个栏目下的库存量
Db.collection.aggregate
(
[
{$group: {_id: "$cat _id", total:{$sum: "$goods _number"}},
]
)
#查询每个栏目下的库存量, and sorted by inventory
Db.collection.aggregate
(
[
{$group: {_id: "$cat _id", total:{$sum: "$goods _number"}},
{$sort: {total:1}}
]
)
#查询每个栏目下的库存量, and sorted by inventory
Db.collection.aggregate
(
[
{$group: {_id: "$cat _id", total:{$sum: "$goods _number"}},
{$sort: {total:1}},
{$limit: 3}
]
)
#查询每个栏目的商品平均价格, and sorted by average price from high to low
Db.collection.aggregate
(
[
{$group: {_id: "$cat _id", avg:{$avg: "$shop _price"}},
{$sort: {avg:-1}}
]
)
MongoDB aggregation Operations Group and Aggregate aggregation framework simple aggregation (10)