2014-02-28 46 views
1

我有一个像这样在我的MongoDB数据:如何算与条件的唯一项目数MongoDB中

db.x.insert({"time" : ISODate("2014-02-29T00:00:00Z"), "user" : "3" }); 
db.x.insert({"time" : ISODate("2014-02-29T00:00:00Z"), "user" : "2" }); 
... 

,我有一个聚合函数来计算在一定时间跨度的活动,

db.x.aggregate([{ 
    "$group":{ 
    "_id": 
     {"$cond":[ 
      {"$and":[ 
       {"$gte": ["$time", ISODate("2014-02-15T00:00:00Z")]}, 
       {"$lt" : ["$time", ISODate("2014-03-01T00:00:00Z")]} 
      ]}, 
      "season1", 
      {"$cond":[ 
       {"$and":[ 
         {"$gte": ["$time", ISODate("2014-03-01T00:00:00Z")]}, 
         {"$lt" : ["$time", ISODate("2014-03-15T00:00:00Z")]} 
        ]}, 
        "season2", 
        null 
      ]} 
     ]}, 
     "count": {"$sum": 1} 
    }}, 
    {"$sort": { "_id": 1 }} 
]) 

它工作正常,像这样

{ 
    "result" : [ 
     { 
      "_id" : "season1", 
      "count" : 7 
     }, 
     { 
      "_id" : "season2", 
      "count" : 7 
     } 
    ], 
    "ok" : 1 
} 

的结果,但我真的停留在如何计算有多少ü每个时代都有哪些用户? 有没有办法做到这一点,而不是每个时间间隔打电话给mongo?

+0

你在哪里与此。你有一个答案,一个错误的答案。它应该显示如何在结果中获得唯一用户 –

回答

0

答案与您的方法相差不远。你很可能缺少的操作是$addToSet运营商,这是在阶段中使用像这样(有也多一点的就说明你做了什么):

db.collection.aggregate([ 

    {"$group":{ 
     "_id": { 

      // This is conditionally setting the _id 
      "$cond":[ 
       // Where between this range 
       {"$and":[ 
        {"$gte": ["$time", ISODate("2014-02-15T00:00:00Z")]}, 
        {"$lt" : ["$time", ISODate("2014-03-01T00:00:00Z")]} 
       ]}, 
       // Set to season1 
       "season1", 
       // Otherwise ... 
       {"$cond":[ 
        // if between this range 
        {"$and":[ 
         {"$gte": ["$time", ISODate("2014-03-01T00:00:00Z")]}, 
         {"$lt" : ["$time", ISODate("2014-03-15T00:00:00Z")]} 
        ]}, 
        // Then it's season2 
        "season2", 
        // otherwise we don't know what it is 
        null 
       ]} 
      ] 
     }, 
     // Just counting the items in the results 
     "count": {"$sum": 1}, 
     // Now get the users 
     "users": {"$addToSet": "$user" }   // Just the unique ones 
    }}, 

    // De-normalise the users from the set 
    {"$unwind": "$users" }, 

    // Now we want to sum things again 
    {"$group": { 
     "_id": "_$id", 
     "count": {"$first": "$count" }, 
     "userCount": {"$sum": 1 } 
    }} 

]) 

所以当我们添加到这使得事物独一无二,数组获得展开这使得事情像他们以前的文件,除了独特的用户现在。

最后一步是,我们只需计数用户条目通过总结1值为每个项目。所有的userCount条目都是一样的,所以当我们$group你只需要其中一个。

最后还有最终结果,还包括计数独特用户。