繁体   English   中英

如何在mongodb中获取子集合的聚合并应用$ count不起作用

[英]How to get aggregation of child collection in mongodb and apply $count is not working

我想对每个信标的计数值求和。 我正在使用汇总查询,但返回的计数为0。如果查询有误,请通知我。

样本数据

 [ { "_id" : ObjectId("5a8166392aa41ec66efc66bf"), "userID" : "5a7c3410bdff0f0014181874", "date" : ISODate("2018-02-08T11:04:54.000Z"), "beacons" : [ { "counts" : "2", "UUID" : "red" }, { "counts" : "1", "UUID" : "blue" } ] }, { "_id" : ObjectId("5a8166392aa41ec66efc66c0"), "userID" : "5a7c3410bdff0f0014181874", "date" : ISODate("2018-02-08T11:04:54.000Z"), "beacons" : [ { "counts" : "2", "UUID" : "red" }, { "counts" : "1", "UUID" : "blue" } ] } ] 

询问

  /* Query */ db.getCollection('CountsDetail') .aggregate([ { "$unwind":"$beacons" }, { "$group": { "_id":"$beacons.UUID", "counts":{ "$sum":"$counts"} } }]); 

响应

  /* Response */ { "_id" : "red", "counts" : 0 } { "_id" : "blue", "counts" : 0 } 

响应返回的总和为0,这很奇怪。 请更正我在做什么错。 谢谢

对不起,小姐,请仔细阅读您的OP。 您的counts字段是嵌套的,因此请使用点符号:

  "counts":{ "$sum":"$beacons.counts"}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM