Home > Software engineering >  Mongodb $min value is greater than $max sometimes
Mongodb $min value is greater than $max sometimes

Time:04-24

I'm fetching date from mongo database and returns $first,$max, $min, and $last, however something very unusual happens - $min is greater than $max. Here's my code:

let Lowestdate = await ETHMongo.aggregate([
  {
    $match: { createdAt: { $gte: new Date(last), $lte: new Date(NEW) } },
  },    
  {
    $group: {
      _id: null,

      minFee_doc: { $first: "$$ROOT" },
      minFee: { $min: "$one" },

      firstFee: { $first: "$one" },
      lastFee: { $last: "$one" },
      maxFee: { $max: "$one" },
    },
  },
]).then((result) => {});

Any solution? Table Heading Wrong results

CodePudding user response:

It looks like your "numbers" are saved as string, in string comparison "99" > "1000000".

Luckily you can solve this very easily, just cast the string to number using $toInt

{
    $group: {
        _id: null,

        minFee_doc: { $first: "$$ROOT" },
        minFee: { $min: {$toInt: "$one"} },

        firstFee: { $first: "$one" },
        lastFee: { $last: "$one" },
        maxFee: { $max: {$toInt: "$one"} },
    },
}
  • Related