skip to Main Content
db.transaction.aggregate(
            [
                {
                    "$match":
                    {"AMOUNT":{"$ne":null}}
                },
                {
                "$group":
                    {"_id":{}}
                },
                {
                    "$addFields":
                    {AMOUNT:{$toDouble:["$AMOUNT"]}}
                },
                {
                "$project":
                {"AMOUNT":{"$gt": 10000}}
                }
            ]
        );

Trying to fetch amount from the collection which is greater than 10000, as I’m working in MongoDB so data is in string format, so I’m using aggregation with $addFields parameter to change the string into the double and then apply the $gt function.

Tried multiple way by arranging query in group but not able to solve it.
Please help

2

Answers


  1. db.collection.find({
      $expr: {
        $gt: [
          {
            $toDouble: "$AMOUNT"
          },
          1000
        ]
      }
    })
    

    You can use same $expr in aggregation function inside $match

    db.collection.aggregate([
      {
        $match: {
          $expr: {
            $gt: [
              {
                $toDouble: "$AMOUNT"
              },
              1000
            ]
          }
        }
      }
    ])
    
    Login or Signup to reply.
  2. Per @Buzz Moschetti suggestion:

    db.collection.aggregate([
      {$match: {$expr: {$gt: [{$toDouble: "$AMOUNT"}, 10000]}}}
    ])
    

    Or:

    db.collection.find(
      {$expr: {$gt: [{$toDouble: "$AMOUNT"}, 10000]}}}
    )
    

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search