-1

See my condition does work fine for my history's first collection but for second it does not work either If I replace my specified id with 5e4a8d2d3952132a08ae5724 that exists in my second object of history's collection return me all data which is not correct because it's date is greater then main collection's date so it should return me nothing please suggest how to fix it.

db.main.aggregate([
  {
    $lookup: {
      from: "history",
      localField: "history_id",
      foreignField: "history_id",
      as: "History"
    }
  },
  {
    $unwind: "$History"
  },
  {
    "$match": {
      $expr: {
        $cond: {
          if: {
            $eq: [
              "5e4a8d2d3952132a08ae5764",
              "$History.user_id"
            ]
          },
          then: {
            $and: [
              {
                $gt: [
                  "$date",
                  "$History.date"
                ]
              },
              {
                $eq: [
                  "5e4a8d2d3952132a08ae5764",
                  "$History.user_id"
                ]
              }
            ]
          },
          else: {}
        }
      }
    }
  }
])

when I put two object into history collection it does not work either MongoPlayground

Here is working playground with single history object https://mongoplayground.net/p/hrNofrq1c3S

Sunil Dubey
  • 123
  • 1
  • 10

1 Answers1

1

The reason, why your query (which is posted in the OP) is not working because, you have not specified anything in else part. So, the better approach will be with '$filter' operator.

You can try the below:

db.main.aggregate([
  {
    $lookup: {
      from: "history",
      localField: "history_id",
      foreignField: "history_id",
      as: "History"
    }
  },
  {
    $project: {
      "History": {
        $filter: {
          input: "$History",
          as: "his",
          cond: {
            $and: [
              {
                $lt: [
                  "$$his.date",
                  "$date"
                ]
              },
              {
                $eq: [
                  "5e4a8d2d3952132a08ae5764",
                  "$$his.user_id"
                ]
              }
            ]
          }
        }
      },
      data: 1,
      history_id: 1,
      sender_id: 1,
      text: 1,
      date: 1
    }
  },
  {
    $unwind: "$History"
  }
])

MongoPlayGroundLink

ngShravil.py
  • 4,742
  • 3
  • 18
  • 30