2012-10-08 91 views
2

我喜歡獲取給定用戶和給定位置的最新進入和退出時間戳。集合是這樣的mongoDB獲取陣列的最新日期

{ "ActivityList" : [ 
{ "type" : "exit", 
     "timestamp" : Date(1348862537170), 
     "user" : { "$ref" : "userProfile", 
     "$id" : ObjectId("4fdeaeeede26fd298262bb80") } }, 
    { "type" : "entry", 
     "timestamp" : Date(1348862546966), 
     "user" : { "$ref" : "userProfile", 
     "$id" : ObjectId("4fdeaeeede26fd298262bb80") } }, 
     { "type" : "entry", 
     "timestamp" : Date(1348870744386), 
     "user" : { "$ref" : "userProfile", 
     "$id" : ObjectId("4fdeaf6fde26fd298262bb81") } }, 
    { "type" : "exit", 
     "timestamp" : Date(1348878233785), 
     "user" : { "$ref" : "userProfile", 
     "$id" : ObjectId("4fdeaf6fde26fd298262bb81") } } ], 
    "Location" : { "$ref" : "loc", 
    "$id" : ObjectId("4fd410f0e7e994b59054b824") }, 
    "_id" : ObjectId("4fe8f3c6e7e9ebe3697ee836") } 

我想是這樣的,但你的幫助不起作用

db.collection.group(
{ 
    keyf: function(doc) { 
     return { 
      location :doc.Location._id, 
      userid  : doc.ActivityList.user._id,   
      actiontype : doc. ActivityList.type 
     }; 
    }, 
    reduce: function(obj,prev) { 
     if (prev.maxdate < obj. ActivityList.timestamp) { 
      prev.maxdate = obj. ActivityList.timestamp; 
     } 
    }, 
    initial: {maxdate:0} 
}); 

感謝。

回答

2

簡單的$group不適用於您的數據結構並查找/過濾數組中的最大值。您必須遍歷數組才能找到最大值,通過檢索文檔並迭代應用程序代碼可以更有效地完成這些操作。

MongoDB中2.2可能的服務器查詢的方法是使用新的Aggregation Framework

db.activity.aggregate(

    // Find matching location documents first (can take advantage of index) 
    { $match : { 
     Location: { 
      "$ref" : "loc", 
      "$id" : ObjectId("4fd410f0e7e994b59054b824") 
     } 
    }}, 

    // Unwind the ActivityList arrays as a document stream 
    { $unwind : "$ActivityList" }, 

    // Filter activities to the user reference of interest 
    { $match : { 
     'ActivityList.user': { 
      "$ref" : "userProfile", 
      "$id" : ObjectId("4fdeaeeede26fd298262bb80") 
     } 
    }}, 

    // Group the stream by activity types, and get the timestamp for the latest of each 
    { $group : { 
     _id : "$ActivityList.type", 
     latest: { $max: '$ActivityList.timestamp' } 
    }} 
) 

樣品結果:

{ 
    "result" : [ 
     { 
      "_id" : "entry", 
      "latest" : ISODate("2012-09-28T20:02:26.966Z") 
     }, 
     { 
      "_id" : "exit", 
      "latest" : ISODate("2012-09-28T20:02:17.170Z") 
     } 
    ], 
    "ok" : 1 
} 
+0

非常感謝。工作沒有問題。看起來我需要努力學習Mongo 2.2中的聚合函數。再次感謝。 – atandon