【问题标题】:Filter data based on lookup value in MongoDB根据 MongoDB 中的查找值过滤数据
【发布时间】:2023-03-15 00:03:01
【问题描述】:

假设我在bookUser 集合中有文档:

{
    'authored_by':ObjectId('asdfs'),
    'general':{'address':{'city':'XYZ'}}
}

{
    'authored_by':ObjectId('jkfo21'),
    'general':{'address':{'city':'YYZ'}}
}

和另一个收集中心_数据为:

{
    'authored_by': ObjectId('asdfs'),
    'books':{'name':'alpha'},
    'book_type':'adventure'
    'general':{'address':{'city':'ABC'}}
}

{
    'authored_by': ObjectId('jkfo21'),
    'books':{'name':'sigma'},
    'book_type':'drama'
    'general':{}
}

我想获取所有对象并从center_data 集合中获取详细信息:

样品 O/P:

[
    {
        'authored_by':ObjectId('asdfs'),
        'general':{'address':{'city':'XYZ'}},
        'books':[
            {
               'address': 'ABC'
            }
        ]
    },
    {
        'authored_by':ObjectId('jkfo21'),
        'general':{'address':{'city':'YYZ'}},
        'books':[
            {
               'address': ''
            }
        ]
    }
]

为此,我尝试了::

db.bookUser.aggregate([
  {
    $lookup: {
      from: "center_data",
      localField: "_id",
      foreignField: "authored_by",
      as: "books"
    }
  },
  {
    $project: {
      books: {
        $filter: {
          input: "$books",
          as: "book",
          cond: {
            $and: [
              {
                $eq: [
                  "book_type",
                  "adventure"
                ]
              }
            ]
          }
        }
      }
    }
  }
])

但是在查询中,它给出了一个空数组。我想从bookUser 集合中获取所有文档并从center_data 集合中获取地址,如果 book_type 不是冒险,则将地址填充为空。

如果有人需要更多信息,请告诉我。

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    担忧

    1. bookUser 集合的文档中没有 _id 字段。根据您提供的数据,localField 应该是authored_by

    2. 从下面的陈述中,您正在比较“book_type”和“adventure”这两个词,这两个词永远不会相同。

    $and:[
      {
        $eq: ['book_type','adventure']
      }
    ]
    

    您需要使用 $$book.book_type 来访问变量值。


    解决方案

    db.bookUser.aggregate([
      {
        $lookup: {
          from: "center_data",
          localField: "authored_by",
          foreignField: "authored_by",
          as: "books"
        }
      },
      {
        $project: {
          authored_by: 1,
          general: 1,
          books: {
            $filter: {
              input: "$books",
              as: "book",
              cond: {
                $and: [
                  {
                    $eq: [
                      "$$book.book_type",
                      "adventure"
                    ]
                  }
                ]
              }
            }
          }
        }
      }
    ])
    

    Sample Mongo Playground

    【讨论】:

    • 感谢您的回复...但是 O/P 中没有 bookUser 的值,只有 center_data 的值。如何做到这一点?请查看示例 O/P。
    • 嗨,很抱歉。完成更新指定要投影的字段的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多