用mongodb计算和分组

时间:2014-08-29 10:04:46

标签: mongodb

我实际上遇到了mongoDB的问题。

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

你能帮我解决这个问题:

“用户的异常数量?”

谢谢大家:D

2 个答案:

答案 0 :(得分:0)

db.treatment.aggregate(
  { 
      $group : {_id : "$anomalies", totalUser : { $sum : 1 }}
  }
);

注意:如果我提出错误,请更改您的collection和文件key name

来源:http://www.mkyong.com/mongodb/mongodb-aggregate-and-group-example/

答案 1 :(得分:0)

因此,如果您的收藏品包含以下文件:

> 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来$ $异常数组的大小

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