Home > database >  Show amount greater than 10000, where amount data type is string in MongoDB
Show amount greater than 10000, where amount data type is string in MongoDB

Time:06-11

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

CodePudding user response:

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
        ]
      }
    }
  }
])

CodePudding user response:

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

  • Related