MongoDB聚合运算之group和aggregate聚集框架简单聚合(10)

时间:2022-12-23 07:11:48

聚合运算之group

语法:

db.collection.group(

{

key:{key1:1,key2:1},

cond:{},

reduce: function(curr,result) {

},

initial:{},

finalize:function() {

}

}

)

key: 分组字段

cond:查询条件

reduce:聚合函数

initial:初始化

finalize:统计一组后的回调函数

#查询每个栏目下的商品数量

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()操作

db.goods.group(

{

key:{cat_id:1},

cond:{},

reduce:function(curr,result) {

result.num += curr.goods_number;

},

initial:{num:0}

}

)

#查询每个栏目最贵的商品价格, max()操作

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;

}

}

)

使用aggregate聚集框架简单聚合

MongoDB聚合运算之group和aggregate聚集框架简单聚合(10)

#查询每个栏目下的商品数量

db.collection.aggregate

(

[

{$group:{_id:"$cat_id",total:{$sum:1}}}

]

);

#查询goods下有多少条商品,select count(*) from goods

db.collection.aggregate

(

[

{$group:{_id:null,total:{$sum:1}}}

]

)

#查询每个栏目下 价格大于50元的商品个数

db.collection.aggregate

(

[

{$match:{shop_price:{$gt:50}}},

{$group:{_id:"$cat_id",total:{$sum:1}}}

]

)

#查询每个栏目下 价格大于50元的商品个数

#并筛选出"满足条件的商品个数" 大于等于3的栏目

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"}}},

]

)

#查询每个栏目下的库存量,并按库存量排序

db.collection.aggregate

(

[

{$group:{_id:"$cat_id" , total:{$sum:"$goods_number"}}},

{$sort:{total:1}}

]

)

#查询每个栏目下的库存量,并按库存量排序

db.collection.aggregate

(

[

{$group:{_id:"$cat_id" , total:{$sum:"$goods_number"}}},

{$sort:{total:1}},

{$limit:3}

]

)

#查询每个栏目的商品平均价格,并按平均价格由高到低排序

db.collection.aggregate

(

[

{$group:{_id:"$cat_id" , avg:{$avg:"$shop_price"}}},

{$sort:{avg:-1}}

]

)