本文介绍了mongodb将排序应用于查找结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有user
和post
集合
{"_id": 1, "name": "User 1"}
{"_id": 2, "name": "User 2"}
{"_id": 1, "title": "Post 1", "userId": 1, "createdAt": ISODate("2017-07-24T04:12:54.255Z")}
{"_id": 2, "title": "Post 2", "userId": 1, "createdAt": ISODate("2017-07-25T04:12:54.255Z")}
{"_id": 3, "title": "Post 1", "userId": 2, "createdAt": ISODate("2017-07-24T04:12:54.255Z")}
如何列出所有用户的最新帖子?就像
How can I list all users with their latest post? Would be something like
{
"_id": 1,
"name": "User 1",
"post": {
"_id": 2,
"title": "Post 2",
"userId": 1,
"createdAt": ISODate("2017-07-25T04:12:54.255Z")
}
}
我知道我可以轻松地使用$ lookup,$ unwind帖子,然后使用post.createdAt进行$ sort,但这使我拥有了冗余用户(用户1将在帖子1和帖子2中列出两次).
I know I can easily use $lookup, $unwind post, then $sort by post.createdAt, but that leave me with redundant user (User 1 will be listed twice for Post 1 and Post 2).
我不知道如何使用$ group删除重复项,同时保持其他字段(名称,post.title等)
I don't know how can I use $group to remove duplicates while keep maintaining other fields (name, post.title, etc)
推荐答案
我使用$ group和$ first
I solved the duplicates using $group and $first
db.getCollection('user').aggregate([
{$lookup: {from: "post", localField: "_id", foreignField: "userId", as: "post"}},
{$unwind: { path: "$post", preserveNullAndEmptyArrays: true }},
{$sort: {"post.createdAt": -1}},
{$group: {"_id": "$_id", "name": {$first: "$name"}, "post": {$first: "$post"}},
{$project: {"_id": 1, "name": 1, post": 1}}
])
随时发布您的答案
这篇关于mongodb将排序应用于查找结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!