2014-02-28 41 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你只需要其中一個。

最後還有最終結果,還包括計數獨特用戶。