mongodb将匹配应用于查找结果

时间:2017-12-01 01:34:08

标签: mongodb

如果我有userpost集合

{"_id": 1, "name": "User 1"}
{"_id": 2, "name": "User 2"}
{"_id": 3, "name": "User 3"}

{"_id": 1, "title": "Post 1", "category": "TRAVEL", "userId": 1, "createdAt": ISODate("2017-07-24T04:12:54.255Z")}
{"_id": 2, "title": "Post 2", "category": "TUTORIAL", "userId": 1, "createdAt": ISODate("2017-07-25T04:12:54.255Z")}
{"_id": 3, "title": "Post 1", "category": "TRAVEL", "userId": 2, "createdAt": ISODate("2017-07-24T04:12:54.255Z")}

我想用最新的帖子返回所有用户。如果他们有帖子,我只需要一个TUTORIAL类别。否则post字段可以为空。我试过这个

db.getCollection('user').aggregate([
    {$lookup: {from: "post", localField: "_id", foreignField: "userId", as: "post"}},
    {$unwind: { path: "$post", preserveNullAndEmptyArrays: true }},
    {$match: {$or: [{"post.category": "TUTORIAL"}, {post: {$exists: false}}]}},
    {$sort: {"post.createdAt": -1}},
    {$group: {"_id": "$_id", "name": {$first: "$name"}, "post": {$first: "$post"}},
    {$project: {"_id": 1, "name": 1, post": 1}}
])

但它只返回用户1和用户3,因为:

  • 用户1在TUTORIAL中有1个帖子,并且匹配$ match condition
  • 用户2在TRAVEL中只有1个帖子且与$ match条件不匹配
  • 用户3没有帖子但匹配$ match condition

如何列出所有用户在TUTORIAL类别中的最新帖子,但仍然包括没有帖子的用户?

1 个答案:

答案 0 :(得分:0)

根据this answer和@ Shubham的评论,我想出了这个

db.getCollection('user').aggregate([
    {$lookup: {from: "post", localField: "_id", foreignField: "userId", as: "posts"}},
    {$project: {"posts": {$filter: {input: "$posts", as: "post", "cond": {$eq: ["$$post.category", "TUTORIAL"]}}}, "_id": 1, "name": 1}}
    {$unwind: { path: "$posts", preserveNullAndEmptyArrays: true }},
    {$sort: {"posts.createdAt": -1}},
    {$group: {"_id": "$_id", "name": {$first: "$name"}, "posts": {$first: "$posts"}},
    {$project: {"_id": 1, "name": 1, posts": 1}}
])

注意我使用$ filter到"查询"的第一个投影。结果来自$ lookup然后" flatten"它与$ unwind