【问题标题】:Mongoose populate first and then filter based on populated fieldMongoose 先填充,然后根据填充的字段进行过滤
【发布时间】:2021-12-17 17:28:05
【问题描述】:

我有两个集合(itemssubitems)。 items 集合在 subItems 属性中具有对子项集合的对象引用(它是子项 ObjectId 的数组)。

我想构建一个查询,我可以首先填充subItems,然后根据填充的字段进行过滤。我尝试运行下面的查询,但似乎最后运行了填充,因此subItems[0].sharedGroups.groupId 永远无法正确过滤,因为它尚未填充。

db.items.find({
        $or: [
          { 'owner': 1 },
          { 'subItems[0].sharedGroups.groupId': { $in: [3691] } },
        ]
}).populate('subItems');

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-populate


    【解决方案1】:

    您应该像这样在聚合中使用$lookup,然后使用$match

    db.items.aggregate([
      {
        $lookup:{
          from:"subItems",
          localField:"subItems", // field of reference to subItem
          foreignField:"_id",
          as :"subItems"
        }},
      {
        $match:
            {
              $or: [
                { 'owner': 1 },
                { 'subItems.sharedGroups.groupId': { $in: [3691] } },
              ]
            }
      }]
      )
    

    【讨论】:

    • 看起来不错,但 subItem.sharedGroups.groupId 没有返回任何东西。我编辑了我的问题,因为 subItem 实际上是一个数组(subItems)
    • 我添加了 $unwind,它现在可以按我的意愿工作
    • 如果您想添加示例数据来完成我的回答,我不知道那种类型
    猜你喜欢
    • 2012-01-22
    • 2018-12-28
    • 2017-05-21
    • 2013-02-10
    • 2020-12-09
    • 2017-02-12
    • 2013-07-06
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多