Home > Back-end >  after aggregation how to check two fields are equal inside a document in mongodb
after aggregation how to check two fields are equal inside a document in mongodb

Time:01-05

  {
    id: 1,
    name: "sree",
    userId: "001",
    paymentData: {
      user_Id: "001",
      amount: 200
    }
  },
  {
    id: 1,
    name: "sree",
    userId: "001",
    paymentData: {
      user_Id: "002",
      amount: 200
    }
  }

I got this result after unwind in aggregation any way to check user_Id equal to userId

CodePudding user response:

Are you looking to only retrieve the results when they are equal (meaning you want to filter out documents where the values are not the same) or are you looking to add a field indicating whether the two are equal?

In either case, you append subsequent stage(s) to the aggregation pipeline to achieve your desired result. If you want to filter the documents, the new stage may be:

  {
    $match: {
      $expr: {
        $eq: [
          "$userId",
          "$paymentData.user_Id"
        ]
      }
    }
  }

See how it works in this playground example.

If instead you want to add a field that compares the two values, then this stage may be what you are looking for:

  {
    $addFields: {
      isEqual: {
        $eq: [
          "$userId",
          "$paymentData.user_Id"
        ]
      }
    }
  }

See how it works in this playground example.

You could also combine the two as in:

  {
    $addFields: {
      isEqual: {
        $eq: [
          "$userId",
          "$paymentData.user_Id"
        ]
      }
    }
  },
  {
    $match: {
      isEqual: true
    }
  }

Playground demonstration here

  • Related