如果我有一个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")}
Run Code Online (Sandbox Code Playgroud)
如何列出所有用户的最新帖子?会是这样的
{
"_id": 1,
"name": "User 1",
"post": {
"_id": 2,
"title": "Post 2",
"userId": 1,
"createdAt": ISODate("2017-07-25T04:12:54.255Z")
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以很容易地使用$ lookup,$ unwind post,然后$ sort by post.createdAt,但是这给我留下了冗余用户(用户1将在Post 1和Post 2中列出两次).
我不知道如何使用$ group删除重复项,同时保持其他字段(名称,post.title等)
luk*_*svo 14
您可以使用新的$lookup语法在单个聚合步骤中解决此问题
db.getCollection('users').aggregate([{
'$lookup': {
'from': 'posts',
'let': {
'userId': '$_id'
},
'pipeline': [{
'$match': { '$expr': { '$eq': ['$userId', '$$userId'] } }
}, {
'$sort': { 'createdAt': -1 }
}, {
'$limit': 10
},
],
'as': 'posts'
}
}
])
Run Code Online (Sandbox Code Playgroud)
注意:未经测试的代码,但原理应该清楚。
spo*_*bob 12
我使用$ group和$ 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}}
])
Run Code Online (Sandbox Code Playgroud)
随意发布您的答案
| 归档时间: |
|
| 查看次数: |
5628 次 |
| 最近记录: |