首页 文章

MongoDB聚合查询分组依据

提问于
浏览
1

假设我有一个包含以下信息的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: 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
}

我想做一个按州分组的订单总价的总和,其中项目是'apple',颜色是'red' . 我的查询是:

{
  $match: {$and: [{item : "apple"}, {color : "red"}]},
  $group: {_id: {state: "$state", cust_id: "$cust_id"}, total: {$sum: "$price"}}
}

但是,我希望能够将_id中包含的结果cust_id设置为数组/映射/某个结构,其中包含构成我的总计的所有客户ID的列表 . 因此我希望我的输出包含

cust_id {'abc123', 'def456'}

有没有办法处理这个mongo聚合/查询?或者也许是一种更好的方法来构建这个查询,这样我可以计算红苹果的成本,按州分组,并包括属于这一类别的所有客户?我将它放在_id部分以便提取信息,但这些数据中包含的任何数据并不重要 . 我想要一种按州分组的方法,并通过上述聚合选择获得所有客户ID的集合 .

1 回答

  • 2

    是的,在聚合$group管道中,您可以使用$addToSet聚合运算符将 cust_id 添加到数组,同时您仍然可以按状态分组:

    db.collection.aggregate([
        {
            "$match": {
                "item": "apple", 
                "color" : "red"
            }
        },
        {
            "$group": {
                "_id": "$state",
                "cust_id": {
                    "$addToSet": "$cust_id"
                },
                "total": {
                    "$sum": "$price"
                }
            }
        }
    ]);
    

    Output

    /* 1 */
    {
        "result" : [ 
            {
                "_id" : "OR",
                "cust_id" : [ 
                    "def456"
                ],
                "total" : 75
            }, 
            {
                "_id" : "CA",
                "cust_id" : [ 
                    "abc123"
                ],
                "total" : 50
            }
        ],
        "ok" : 1
    }
    

相关问题