2015-12-08 46 views
0

對於NoSQL和Mongoose,我是一個新手。我一直在尋找一點,但無法真正找到我要找的東西(這讓我更難以知道答案)。Mongoose NodeJS - 查找每個用戶的最後一條插入記錄

基本上,我有一個用戶正在添加的記錄列表。這些記錄包含一些數據,我想要列出每個用戶最新插入的消息。

在SQL中,我會寫;

SELECT * FROM records ORDER BY inserted_date GROUP BY user_id; 

這會返回一個像這樣的集合;

[ 
    {user: 2, insert_date: 2015-08-12T15:15:00, message: "Hi"}, 
    {user: 3, insert_date: 2015-08-12T15:12:00, message: "Also hi"}, 
    {user: 5, insert_date: 2015-08-12T15:14:00, message: "Not hi"} 
] 

我一直在環顧四周,發現一些答案,但這些似乎並沒有工作。

我試過了;

https://stackoverflow.com/a/7570091/1493455

和其他一些總的thingie像這樣;

Record.aggregate(
    {}, 
    { 
     $group: { 
      _id: '$user_id', 
      inserted: { $last: "$inserted" }, 
      message: { $last: "$message" } 
     } 
    }, 
    function(err, messages) { 
     console.log(err, messages); 
    } 
); 

我從另一個答案複製 - 但我真的不明白它在做什麼,甚至應該做什麼。

我當然可以爲每個用戶使用排序和限制查詢,但這看起來效率很低。

我很高興,如果有人能在正確的方向:)點我

+0

我剛剛可能發現了一個重複的問題; http://stackoverflow.com/questions/29410749/mongoose-find-last-message-from-each-user?rq=1我會在一秒鐘內回覆。 –

回答

0

是的,重複的:Mongoose - find last message from each user

我結束了我的固定代碼;

Record.aggregate(
    [ 
     // Matching pipeline, similar to find 
     { 
      "$match": {} 
     }, 
     // Sorting pipeline 
     { 
      "$sort": { 
       "inserted": -1 
      } 
     }, 
     // Grouping pipeline 
     { 
      "$group": { 
       "_id": "$user_id", 
       "message": { 
        "$first": "$message" 
       }, 
       "inserted": { 
        "$first": "$inserted" 
       } 
      } 
     }, 
     // Project pipeline, similar to select 
     { 
      "$project": { 
       "_id": 0, 
       "user_id": "$_id", 
       "message": 1, 
       "inserted": 1 
      } 
     } 
    ], 
    function(err, messages) { 
     console.log(err, messages); 
    } 
); 

和更新,以代替舊(2.x的)我是運行最新的MongoDB(3.4)(這給出錯誤,因爲總尚不支持)。

相關問題