Mongodb 使用mongo db进行计数和分组

Mongodb 使用mongo db进行计数和分组,mongodb,Mongodb,我实际上面临着mongoDB的一个问题 我需要显示一些统计数据: -治疗是包含日期、治疗用户和异常列表的信息 您能否帮助我请求获得: 用户异常的数量 谢谢大家:D db.treatment.aggregate( { $group : {_id : "$anomalies", totalUser : { $sum : 1 }} } ); 注意:如果我输入错误,请更改集合和文档密钥名称 来源:因此,如果您的收藏有以下文档: > db.treatments.find()

我实际上面临着mongoDB的一个问题

我需要显示一些统计数据: -治疗是包含日期、治疗用户和异常列表的信息

您能否帮助我请求获得:

用户异常的数量

谢谢大家:D

db.treatment.aggregate(
  { 
      $group : {_id : "$anomalies", totalUser : { $sum : 1 }}
  }
);
注意:如果我输入错误,请更改集合和文档密钥名称


来源:

因此,如果您的收藏有以下文档:

> db.treatments.find()
{ "_id" : 1, "date" : ISODate("2014-08-29T15:44:45.843Z"), "user" : "A", "anomalies" : [ "a", "b", "c" ] }
{ "_id" : 2, "date" : ISODate("2014-08-29T15:45:01.782Z"), "user" : "A", "anomalies" : [ "e", "f", "g" ] }
{ "_id" : 3, "date" : ISODate("2014-08-29T15:45:34.889Z"), "user" : "B", "anomalies" : [ "a", "b", "c", "e", "f", "g" ] }
{ "_id" : 4, "date" : ISODate("2014-08-29T15:48:01.860Z"), "user" : "B", "anomalies" : [ "a", "b", "c", "e", "f", "g" ] }
{ "_id" : 5, "date" : ISODate("2014-08-29T15:48:28.937Z"), "user" : "A", "anomalies" : [ "x", "y", "z" ] }
您可以使用$group stage对数组的$size进行$sum

> db.treatments.aggregate([ { $group: { _id: "$user", allAnomalies: { $sum: { $size: "$anomalies" } } } } ] )
{ "_id" : "B", "allAnomalies" : 12 }
{ "_id" : "A", "allAnomalies" : 9 }

计算异常用户的数量非常有效,但我需要显示:用户1=>50个异常,用户2=>60个异常,用户3=>10个异常。我为您提供了分组异常查询。如果您希望按用户查询分组,那么请尝试使用$user而不是$exceptions.J,实际上是在尝试使其工作。但我想我需要时间