2013-09-23 20 views
25

ben MongoDB aşağıdaki verileri vardır:mongodb toplamı sorgu Örneğin

{ "_id" : ObjectId("524091f99c49c4c3f66b0e46"), "hour" : 10, "incoming", 100} 
{ "_id" : ObjectId("5240a045dbeff33c7333aa51"), "hour" : 11, "incoming", 200} 
{ "_id" : ObjectId("5240a2ecda0d37f35c618aca"), "hour" : 12, "incoming", 300} 

Şimdi sorgulamak istiyorum "SUM gelen 11 arasındaki sayıları - 12" (500 sonuç olmalıdır), nasıl yapabilirdim Mongo Shell kullanarak bunu yapmak?

+3

kontrol edin: Ayrıca sadece, boru hattının sonunda bir $ proje operatörü ekleyerek toplamı ihtiva şöyle elde edilen belgeyi şekillendirebilir

db.CollectionNameGoesHere.aggregate({ $match: { $and: [ { hour: { $gte: 11 } }, { hour: { $lte: 12 } } ] } }, { $group: { _id : null, sum : { $sum: "$incoming" } } }); 

: Burada gibi sorgu görüneceğini var MongoDB'nin [toplama çerçevesi] (http://docs.mongodb.org/manual/reference/aggregation/). Özellikle, ['$ match'] (http://docs.mongodb.org/manual/reference/aggregation/match/#pipe._S_match), [' $ group'] 'a bir göz atın (http: // docs). .mongodb.org/manual/reference/aggregation/group/# pipe._S_group) ve ['$ sum'] (http://docs.mongodb.org/manual/reference/aggregation/sum/#grp._S_sum) . – llovett

cevap

36

llovet'in önerdiği gibi, toplama çerçevesi gitmenin yoludur.

{ $project: { _id: 0, sum: 1 } }