繁体   English   中英

MongoDB 聚合查询,基于参数返回作为模型引用的集合

[英]MongoDB aggregation query, return collections that that are refs on model, based on a paramater

我有以下查询,

MyModel.aggregate([
    {
      $project: {
        field: 1,
      }
    },
    {
      $lookup: {
        from: "AnotherModel",
        localField: "_id",
        foreignField: "someField",
        as: "field"
      },
    },
    {
      $unwind: {
        path: "$_id"
      }
    }
])

这工作执行,但不像预期的那样。 AnotherModel ,有一个叫做场show ,我想这个查询返回MyModel集合,只在show设置为true AnotherModel 我试过,

MyModel.aggregate([
    {
      $project: {
        field: 1,
      }
    },
    {
      $lookup: {
        from: "AnotherModel",
        localField: "_id",
        foreignField: "someField",
        as: "field"
      },
      $where: {
        show: true // <-- this part
      }
    },
    {
      $unwind: {
        path: "$_id"
      }
    }
])

但这引发了错误。 我怎样才能做到这一点?

试试这个: 不相关的子查询

MyModel.aggregate([
  {
    $project: {
      field: 1
    }
  },
  {
    $lookup: {
      from: "AnotherModel",
      let: {
        id: "$_id"
      },
      pipeline: [
        {
          $match: {
            show: true,
            $expr: {
              $eq: [
                "$someField",
                "$$id"
              ]
            }
          }
        }
      ],
      as: "field"
    }
  },
  {
    $unwind: {
      path: "$_id"
    }
  }
])

蒙戈游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM