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

问题描述 投票:1回答:1

我有以下查询,

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

此作品已执行,但未如预期。在AnotherModel中,有一个名为show的字段,我希望此查询返回MyModel集合,只有在show上将AnotherModel设置为true的情况下。我尝试过,

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

但是那引发了一个错误。我该如何实现?

node.js mongodb mongoose aggregation-framework
1个回答
2
投票
尝试这个:Uncorrelated Sub-queries

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

MongoPlayground
© www.soinside.com 2019 - 2024. All rights reserved.