【问题标题】:mongodb apply match to lookup resultsmongodb 将匹配应用于查找结果
【发布时间】:2017-12-01 01:34:08
【问题描述】:

如果我有 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")}

我想返回所有用户的最新帖子。如果他们有帖子,我只需要一个教程类别。否则,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 条件
  • 用户 2 在 TRAVEL 中只有 1 个帖子,且不符合 $match 条件
  • 用户 3 没有帖子,但符合 $match 条件

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

【问题讨论】:

  • 而不是在投影阶段展开和匹配使用过滤器
  • @Shubham 嘿,你是对的!我刚刚在下面发布了我的答案。干杯。

标签: mongodb


【解决方案1】:

根据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 “查询”结果,然后用 $unwind “展平”它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2018-05-15
    • 2016-02-07
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多