【问题标题】:In MongoDb find method, how to set GTE and LTE option in both?在 MongoDb find 方法中,如何同时设置 GTE 和 LTE 选项?
【发布时间】:2022-11-21 15:22:49
【问题描述】:

有一张桌子领域。 (字符串类型)

在此表中,我想搜索 gte 和 lte 之间的一些行。

如果行是这样的,

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

我想搜索 2022 到 2025 之间的值。

为此,我编写了这样的代码。

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

但是,发生了这个错误。

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

你能告诉我这些问题的解决方案吗??

此外,我在此环境中对其进行了测试。 Mongo Palyground

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您错过了 $and 运算符。并分别用 {} 包装 $gte$lte

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

    Demo @ Mongo Playground

    【讨论】:

    • 哦,缺少选项!太感谢了
    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 2019-05-04
    • 2023-04-09
    • 1970-01-01
    • 2016-11-17
    • 2021-09-17
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多