[英]Mongoose NodeJS - Find the last inserted record per user
在NoSQL和Mongoose方面,我是個新手。 我一直在搜索,但無法真正找到我想要的東西(這使我更不知道答案的難度更大)。
基本上,我有一個由用戶添加的記錄列表。 這些記錄包含一些數據,我想列出每個用戶的最新插入消息列表。
在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
還有其他一些聚合的東西,就像這樣;
Record.aggregate(
{},
{
$group: {
_id: '$user_id',
inserted: { $last: "$inserted" },
message: { $last: "$message" }
}
},
function(err, messages) {
console.log(err, messages);
}
);
我已經從另一個答案中復制了該內容-但我並不十分了解它在做什么,甚至應該做什么。
我當然可以為每個用戶使用排序和限制查詢,但這似乎效率很低。
如果有人可以指出正確的方向,我會很高興的:)
是的,重復的: 貓鼬-查找每個用戶的最后一條消息
我最終用修改了我的代碼;
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);
}
);
並更新到最新的mongodb(3.4)而不是我正在運行的舊版本(2.x)(這會產生錯誤,因為還不支持聚合)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.