MongoDB查询分组依据

时间:2013-05-27 06:58:33

标签: mongodb aggregation-framework

我在测试集合中使用这种格式的数据

{car_id: "1", owner_id: "a"}
{car_id: "1", owner_id: "b"}
{car_id: "1", owner_id: "c"}
{car_id: "1", owner_id: "d"}
{car_id: "1", owner_id: "a"}
{car_id: "1", owner_id: "b"}
{car_id: "1", owner_id: "c"}
{car_id: "1", owner_id: "d"}
{car_id: "2", owner_id: "a"}
{car_id: "2", owner_id: "b"}
{car_id: "2", owner_id: "c"}
{car_id: "2", owner_id: "d"}
{car_id: "2", owner_id: "a"}
{car_id: "2", owner_id: "b"}
{car_id: "2", owner_id: "c"}
{car_id: "2", owner_id: "d"}
{car_id: "3", owner_id: "a"}
{car_id: "3", owner_id: "b"}
{car_id: "3", owner_id: "c"}
{car_id: "3", owner_id: "a"}
{car_id: "3", owner_id: "b"}
{car_id: "3", owner_id: "c"}
{car_id: "3", owner_id: "d"}
{car_id: "3", owner_id: "e"}
    ...

我们需要以这种方式查询后输出

{
    "result" : [
        {
            "for_cars_id" : 1,
            "owner_id" : "a",
            "owner_id_count: 2
        },
        {
            "for_cars_id" : 1,
            "owner_id" : "b",
            "owner_id_count: 2
        },
        {
            "for_cars_id" : 1,
            "owner_id" : "c",
            "owner_id_count: 2
        },
        {
            "for_cars_id" : 1,
            "owner_id" : "d",
            "owner_id_count: 2
        },
        {
            "for_cars_id" : 2,
            "owner_id" : "a",
            "owner_id_count: 2
        },
        {
            "for_cars_id" : 2,
            "owner_id" : "b",
            "owner_id_count: 2
        }
                       ...
                       ...

    ],
    "ok" : 1
}

我尝试在链接(Group count with MongoDB using aggregation framework)的帮助下执行此操作但未获得相应的结果请帮助我如何找到此输出

感谢

1 个答案:

答案 0 :(得分:1)

这非常简单:

db.test.aggregate({
  $group: {
    _id: {
      car_id: "$car_id",
      owner_id: "$owner_id"
    },
    owner_id_count: { $sum: 1 }
  }
}, {
  $project: {
    _id: 0,
    for_cars_id: "$_id.car_id",
    owner_id: "$_id.owner_id",
    owner_id_count: 1
  }
})