MongoDB聚合查询分组依据
假设我有一个包含以下信息的MongoDB集合:MongoDB聚合查询分组依据,mongodb,mongoid,aggregation-framework,Mongodb,Mongoid,Aggregation Framework,假设我有一个包含以下信息的MongoDB集合: { cust_id: "abc123", ord_date: ISODate("2012-11-02T17:04:11.102Z"), state: 'CA', price: 50, item: apple, color: red } { cust_id: "abc123", ord_date: ISODate("2012-11-02T17:04:11.102Z"), state: 'WA', price:
{
cust_id: "abc123",
ord_date: ISODate("2012-11-02T17:04:11.102Z"),
state: 'CA',
price: 50,
item: apple,
color: red
}
{
cust_id: "abc123",
ord_date: ISODate("2012-11-02T17:04:11.102Z"),
state: 'WA',
price: 25,
item: apple,
color: green
}
{
cust_id: "abc123",
ord_date: ISODate("2012-11-02T17:04:11.102Z"),
state: 'CA',
price: 75,
item: orange,
color: orange
}
{
cust_id: "def456",
ord_date: ISODate("2012-11-02T17:04:11.102Z"),
state: 'OR',
price: 75,
item: apple,
color: red
}
我想计算按州分组的订单总价的总和,其中项目为“苹果”,颜色为“红色”。我的问题是:
{
$match: {$and: [{item : "apple"}, {color : "red"}]},
$group: {_id: {state: "$state", cust_id: "$cust_id"}, total: {$sum: "$price"}}
}
但是,我希望能够将我的结果cust_id包含在_id中,它是一个数组/map/some结构,其中包含构成我的总计的所有客户id的列表。因此,我希望我的输出包含
cust_id {'abc123', 'def456'}
是否有办法处理此mongo聚合/查询?或者是一种更好的方式来组织这个查询,这样我就可以按州分组,计算红苹果的总成本,并包括属于这个类别的所有客户?我把它放在_id部分是为了提取信息,但这些数据是否包含在其中并不重要。我想要一种按状态分组的方法,并通过上述聚合选择获取所有客户id的集合。是的,在聚合管道中,您可以使用聚合操作符将客户id添加到数组中,同时您仍然可以按状态分组:
db.collection.aggregate([
{
"$match": {
"item": "apple",
"color" : "red"
}
},
{
"$group": {
"_id": "$state",
"cust_id": {
"$addToSet": "$cust_id"
},
"total": {
"$sum": "$price"
}
}
}
]);
输出:
/* 1 */
{
"result" : [
{
"_id" : "OR",
"cust_id" : [
"def456"
],
"total" : 75
},
{
"_id" : "CA",
"cust_id" : [
"abc123"
],
"total" : 50
}
],
"ok" : 1
}
谢谢正是我需要的@fowlball1010别担心:-)