简体   繁体   中英

multiple match on condition after aggregate lookup in mongodb

db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: ids
      }
    }
  },
  {
    $lookup: {
      from: "admin",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  {
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },

])

I am getting one value but even expected multiple data which are greater then equal to 01 jan 2020. How can I fix it please guide thanks

You have to unwind the result after lookup to perform $match .

db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: ids
      }
    }
  },
  {
    $lookup: {
      from: "admin",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  { $unwind: "$data"}
  {
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },
  {
    $group: {
        _id: "$_id",
        status: { "$first": "$status" },
        deleted_at: { "$first": "$deleted_at" }, //You can project more 
        data: { "$push": "$data" }
    }
  }
])

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