首页 > 解决方案 > $gte 和 $lte 运算符 mongo 按数字过滤字符串字段

问题描述

我在 MongoDB 中有一个包含多年经验的字符串字段,例如“1 年”、“3 年”等。

我需要按数字过滤此字段

db.collection.find({ experience: {'$gte': '1', 'lte': '3'} })

但它按字符串过滤,即“$gte”:“10”返回 3、4、7 等,比较字符串。

我试图创建和索引

db.profiles.createIndex( { experience: 1 }, { collation: { numericOrdering: true, locale: "en_US" } } )

但它没有用。有任何想法吗?

标签: mongodb

解决方案


您必须将字符串转换为数字,然后您可以对其进行过滤:

db.collection.aggregate([
  {
    $addFields: {
      regex: {
        $regexFind: {
          input: "$experience",
          regex: "^\\d+"
        }
      }
    }
  },
  {
    $set: {
      experience_num: {
        $convert: {
          input: "$regex.match",
          to: "int"
        }
      }
    }
  },
  {$match: {experience_num: {"$gte": 1, "$lte": 3}}},
  {$project: {experience: 1}}
])

蒙古游乐场

  1. 仅从字符串中选择数字
  2. 将数字字符串转换为整数值
  3. 按数字过滤 >= 3 和 <=1
  4. 移除我们添加的额外属性

推荐阅读