2015-02-09 33 views
3

如果我有這樣一個集合:合併多個團體聚集在MongoDB中

{ 
    "store" : "XYZ", 
    "total" : 100 
}, 
{ 
    "store" : "XYZ", 
    "total" : 200 
}, 
{ 
    "store" : "ABC", 
    "total" : 300 
}, 
{ 
    "store" : "ABC", 
    "total" : 400 
} 

我可以聚集拿到訂單的$sum集合中:

db.invoices.aggregate([{$group: { _id: null, total: { $sum: "$total"}}}]) 

{ 
    "result": [{ 
      "_id": null, 
      "total": 1000 
     } 
    ], 
    "ok": 1 
} 

,我可以得到按商店分組的訂單的$sum

db.invoices.aggregate([{$group: { _id: "$store", total: { $sum: "$total"}}}]) 

{ 
    "result": [{ 
      "_id": "ABC", 
      "total": 700 
     }, { 
      "_id": "XYZ", 
      "total": 300 
     } 
    ], 
    "ok": 1 
} 

但我該如何做到這一點一個查詢?

回答

10

你可以如下彙總:

  • $groupstore場,計算subtotal

  • $projectdoc保持subtotal組圓通,接下來 組中。

  • $groupnull累計淨收益。

代碼:

db.invoices.aggregate([{ 
      $group: { 
       "_id": "$store", 
       "subtotal": { 
        $sum: "$total" 
       } 
      } 
     }, { 
      $project: { 
       "doc": { 
        "_id": "$_id", 
        "total": "$subtotal" 
       } 
      } 
     }, { 
      $group: { 
       "_id": null, 
       "total": { 
        $sum: "$doc.total" 
       }, 
       "result": { 
        $push: "$doc" 
       } 
      } 
     }, { 
      $project: { 
       "result": 1, 
       "_id": 0, 
       "total": 1 
      } 
     } 
    ]) 

輸出:

{ 
    "total": 1000, 
    "result": [{ 
      "_id": "ABC", 
      "total": 700 
     }, { 
      "_id": "XYZ", 
      "total": 300 
     } 
    ] 
} 
+0

你真棒,謝謝! – 2015-02-10 03:35:29

+0

只是!順便說一句。像這樣的聚合..只是爲這種多個分組/投影調用2個單獨的調用更有效率? – 2015-02-10 05:04:17

+1

@MattKim - 謝謝。儘管聚合解決方案涉及多個階段,但它比兩次數據庫調用,然後在應用程序代碼中進行一些後處理有效地工作。如果解決方案涉及諸如'$ unwind'等非常昂貴的階段,則情況將會不同。 – BatScream 2015-02-10 05:09:24