2013-05-27 65 views
0

我以這種格式在測試收集數據已經MongoDB的查詢組由

{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

這很簡單:

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