mongodb - $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" } } )
但它没有用。有任何想法吗?
解决方案
您必须将字符串转换为数字,然后您可以对其进行过滤:
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}}
])
- 仅从字符串中选择数字
- 将数字字符串转换为整数值
- 按数字过滤 >= 3 和 <=1
- 移除我们添加的额外属性
推荐阅读
- javascript - 是否可以在文档准备好之前进行一些客户端 DOM 操作?
- python-3.x - “如何在使用类时更正语法错误和定义错误”
- sql - 如何在 SSRS 的现有报表中添加新字段?添加的字段显示 SQL 查询而不是返回值
- c - 在 strcpy 函数中使用指针作为参数。试图从书中理解代码
- date - 如何在 React Native 中获取当前日期
- java - Struts2:具有多个参数的getText未填充
- leaflet - 在 Leaflet 的矢量图层上的弹出窗口中获取目标的 FeatureId
- php - 我可以使用 Laravel 5.7 迁移来移动列吗?
- git - 如何列出今年 git 提交的时间戳和提交消息?
- python - 如何通过 sys.argv 执行函数