2016-06-07 113 views
0

我在我的收藏文件喜歡:查詢嵌套數組中元素的總數 - 嵌入文檔的MongoDB

{ 
    _id: 1, 
    activities: [ 
    { 
     activity_id: 1, 
     travel: [ 
     { 
      point_id: 1, 
      location: [-76.0,19.1] 
     }, 
     { 
      point_id: 2, 
      location: [-77.0,19.3] 
     } 
     ] 
    }, 
    { 
     activity_id: 2, 
     travel: [ 
     { 
      point_id: 3, 
      location: [-99.3,18.2] 
     } 
     ] 
    } 
    ] 
}, 
{ 
    _id: 2, 
    activities: [ 
    { 
     activity_id: 3, 
     travel: [ 
     { 
      point_id: 4, 
      location: [-75.0,11.1] 
     } 
     ] 
    } 
    ] 
} 

我能得到的活動總數,如下:

db.mycollection.aggregate(
    {$unwind: "$activities"}, 
    {$project: {count:{$add:1}}}, 
    {$group: {_id: null, number: {$sum: "$count" }}} 
) 

我得到(3個活動):

{ "result" : [ { "_id" : null, "number" : 3 } ], "ok" : 1 } 

問題:何我能獲得所有旅行中的元素總數嗎?

預期的結果:4元件

它們是:

{ 
    point_id: 1, 
    location: [-76.0,19.1] 
}, 
{ 
    point_id: 2, 
    location: [-77.0,19.3] 
}, 
{ 
    point_id: 3, 
    location: [-99.3,18.2] 
}, 
{ 
    point_id: 4, 
    location: [-75.0,11.1] 
} 
+1

其實這是和仍然像'db.mycollection.aggregate簡單({「$組「:{」_id「:null,」total「:{」$ sum「:{」$ sum「:{」$ map「:{」input「:」$ activities「,」as「:」a「, 「in」:{「$ size」:「$$ a.travel」}}}}}}})'。這是因爲'$ sum'可以直接用於數組,也可以作爲自MongoDB 3.2以來的累加器。通過您自己刪除的答案,您目前的MongoDB版本似乎比這個要舊得多。 –

回答

1

可以很容易地通過使用雙$unwind

例如變換文件

db.collection.aggregate([ 
    {$unwind: "$activities"}, 
    {$unwind: "$activities.travel"}, 
    {$group:{ 
    _id:null, 
    travel: {$push: { 
     point_id:"$activities.travel.point_id", 
     location:"$activities.travel.location"}} 
    }}, 
    {$project:{_id:0, travel:"$travel"}} 
]) 

這將發出非常接近你想要的輸出格式:

{ 
    "travel" : [ 
     { 
      "point_id" : 1.0, 
      "location" : [ 
       -76.0, 
       19.1 
      ] 
     }, 
     { 
      "point_id" : 2.0, 
      "location" : [ 
       -77.0, 
       19.3 
      ] 
     }, 
     { 
      "point_id" : 3.0, 
      "location" : [ 
       -99.3, 
       18.2 
      ] 
     }, 
     { 
      "point_id" : 4.0, 
      "location" : [ 
       -75.0, 
       11.1 
      ] 
     } 
    ] 
} 

更新:

如果你只是想知道在整個集合旅行證件的總數,

試試看:

db.collection.aggregate([ 
    {$unwind: "$activities"}, 
    {$unwind: "$activities.travel"}, 
    {$group: {_id:0, total:{$sum:1}}} 
]) 

它會打印:

{ 
    "_id" : NumberInt(0), 
    "total" : NumberInt(4) 
} 

更新2:

OP希望基於在聚合框架某些屬性過濾文件。這裏有一個方法可以這樣做:

db.collection.aggregate([ 
    {$unwind: "$activities"}, 
    {$match:{"activities.activity_id":1}}, 
    {$unwind: "$activities.travel"}, 
    {$group: {_id:0, total:{$sum:1}}} 
]) 

它將打印(基於樣本文檔):

{ "_id" : 0, "total" : 2 } 
+0

這是完美的,非常感謝.....我不知道雙'$ unwind' –

+0

可能加入參數'{$ match:{「activities.activity_id」:1}}''所以我可以得到特定活動的旅行清單? .... 怎麼做 ? –

+0

確實,你可以做到這一點。請參閱$匹配 – Saleem