0

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

{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
}

我尝试在链接的帮助下做到这一点(使用聚合框架对 MongoDB 进行组计数)但没有得到适当的结果,请帮助我如何找到这个输出

谢谢

4

1 回答 1

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
  }
})
于 2013-06-12T19:57:15.787 回答