简体   繁体   中英

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

I have the following query,

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

This works executes, but not as expected. In AnotherModel , there is a field called show , and I want this query to return MyModel collections, only where show is set to true on AnotherModel . I tried,

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

But that threw an error. How can I achieve this?

Try this one: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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