2016-05-14 36 views
2

我是MongoDB世界的新成員。獲取另一個字段的聚合記錄

我已經在我的收藏以下數據

{ 
    "_id" : ObjectId("5735d8d4d147aa34e440988f"), 
    "DeviceLogId" : "26962", 
    "DeviceId" : "10", 
    "UserId" : "78", 
    "LogDateTime" : ISODate("2016-05-12T07:52:44.000+0000") 
} 
{ 
    "_id" : ObjectId("5735d8d4d147aa34e4409890"), 
    "DeviceLogId" : "26963", 
    "DeviceId" : "10", 
    "UserId" : "342", 
    "LogDateTime" : ISODate("2016-05-12T07:54:09.000+0000") 
} 
{ 
    "_id" : ObjectId("5735d8d4d147aa34e4409891"), 
    "DeviceLogId" : "26964", 
    "DeviceId" : "10", 
    "UserId" : "342", 
    "LogDateTime" : ISODate("2016-05-12T07:54:10.000+0000") 
} 
{ 
    "_id" : ObjectId("5735d8d4d147aa34e4409892"), 
    "DeviceLogId" : "26965", 
    "DeviceId" : "10", 
    "UserId" : "78", 
    "LogDateTime" : ISODate("2016-05-12T07:54:27.000+0000") 
} 

我想用組通過查詢每個用戶的DeviceId最大LogDateTime

我已經寫了如下查詢組,但不知道如何獲得每條記錄的DeviceLogId

collectionName.aggregate(
     [{ 
      $match: { LogDateTime: { $gt: todaysDateStart, $lt: todayDateEnd } } 
     }, { 
      $group: { 
       _id: "$UserId", 
       maxPunchTime: { $max: { $add: [ "$LogDateTime", 330*60000 ] } }, 
      } 
     }]) 

在MSSQL中,我可以很容易地使用嵌套查詢,但我不知道如何實現在MongoDB中。

在此先感謝。

回答

2

使用$addToSet Group Accumulator

collectionName.aggregate(
    [{ 
     $match: { LogDateTime: { $gt: todaysDateStart, $lt: todayDateEnd } } 
    } 
    , { 
     $group: { 
      _id: "$UserId", 
      maxPunchTime: { $max: { $add: [ "$LogDateTime", 330*60000 ] } },    
      deviceLogIds:{$addToSet: "$DeviceLogId"} //<---- 
     } 
    } , 
    { $sort: {"maxPunchTime" : -1} } , {$limit : 1} //Sort Descending + Limit to 1 
    ]) 
+0

我不想設定DeviceLogId'的'。我只想要一個具有最大「LogDateTime」的'DeviceLogId'。 – shashwat

+0

你測試了我給你的代碼嗎? – Atchoum

+0

是的,我試過了。它給了我一個'DeviceLogIDs'數組。我不知道選哪一個。 – shashwat

0

添加設備ID在小組賽階段的陣列,

Device:{$addToSet:deviceId}