Home > Enterprise >  MongoDB - How to set $gte and $lte options in .find() method
MongoDB - How to set $gte and $lte options in .find() method

Time:11-22

There is a table that has a year field. (string type)

At this table, I'd like to search some rows between $gte and $lte.

If the rows are like these:

[
  {
    "year": "2022"
  },
  {
    "year": "2023"
  },
  {
    "year": "2024"
  },
  {
    "year": "2024"
  },
  {
    "year": "2025"
  },
  {
    "year": "2026"
  },
  {
    "year": "2028"
  },
  {
    "year": "2030"
  },
  {
    "year": "2036"
  }
]

I'd like to search the values between 2022 and 2025.

For that purpose, I wrote the code like this.

db.collection.find({
  $expr: {
    $gt: [
      {
        $toInt: "$year"
      },
      2022
    ],
    $lte: [
      {
        $toInt: "$year"
      },
      2025
    ]
  }
})

But, this error occurred.

query failed: (Location15983) An object representing an expression must have exactly one field: { $gt: [ { $toInt: "$year" }, 2022.0 ], $lte: [ { $toInt: "$year" }, 2025.0 ] }

Could you tell me the solution to this problem?

Additionally, I tested it in this environment. Mongo Playground

CodePudding user response:

You miss out the $and operator. And wrap $gte and $lte with a {} respectively.

db.collection.find({
  $expr: {
    $and: [
      {
        $gt: [
          {
            $toInt: "$year"
          },
          2022
        ]
      },
      {
        $lte: [
          {
            $toInt: "$year"
          },
          2025
        ]
      }
    ]
  }
})

Demo @ Mongo Playground

  • Related