2013-10-29 79 views
3

考慮下面的數據庫的集合:求和蒙戈子文檔字段

> db.collection.find() 
{ "_id" : 1, "results" : { "record" : { "price" : 100 } } } 
{ "_id" : 2, "results" : { "record" : { "price" : 200 } } } 
{ "_id" : 3, "results" : { "record" : { "price" : 300 } } } 

如何我可以使用聚合(或映射簡化),以獲得各results.record.price字段的總和?

> db.collection.aggregate({$group : { _id:"", "results.record.price" : {$sum : "$results.record.price"}}}, {$project:{_id: 0, "results.record.price" : "$results.record.price"}}) 
Error: Printing Stack Trace 
    at printStackTrace (src/mongo/shell/utils.js:37:15) 
    at DBCollection.aggregate (src/mongo/shell/collection.js:897:9) 
    at (shell):1:15 
Mon Oct 28 20:15:24.065 aggregate failed: { 
     "errmsg" : "exception: the group aggregate field name 'results.record.price' cannot be used because $group's field names cannot contain ' 
.'", 
     "code" : 16414, 
     "ok" : 0 
} at src/mongo/shell/collection.js:898 

回答

3

試試這個。

db.collection.aggregate({$group : {_id: "", total : {$sum: "$results.record.price"}}}, {$project: {_id: 0, total: 1}}) 
+0

'_id:「」'是什麼意思?感謝您的幫助 –

+0

@kevin'_id'是組標識符。在那種情況下,由於它是不變的,空字符串,每個處理的記錄將被合併成一個組,由該空字符串標識。你可以使用其他常量,比如'null',''a「'等等。 – Rafa

+0

你能否檢查一下 - http://stackoverflow.com/questions/19664748/summing-mongo-sub-document-array –