字符串转换成数值进行查询
数据
{
"_id": ObjectId("61e4e80a55170000420035a7"),
"a": "6",
"v": "8"
}
{
"_id": ObjectId("61e4e80a55170000420035a7"),
"a": "6",
"v": "20"
}
{
"_id": ObjectId("61e51e0355170000420035a8"),
"a": "6",
"v": "2021-01-06"
}
db.test_list.aggregate([
// 将字符串转换成double数值
{"$project":{"a":1,"v":{"$convert":{"input":"$v","to":"double", "onError": "$v","onNull":"missing time"}} }},
//查询大于等于20的
{"$match": {"v":{"$gte":20}}}
])
$convert (字段类型转换)
{"$project":{"a":1,"v":{"$convert":{"input":"$v","to":"double", "onError": "$v","onNull":"missing time"}} }
{
$convert:
{
input: "来源字段",
to: “准备转换成的类型”,
onError: "如果无法转换则输出", // Optional.
onNull: "如果字符串不存在则输出" // Optional.
}
}
- 支持的转换成的数据类型
"double"
1
"string"
2
For more information on the conversion to string, see Converting to a String.
"objectId"
7
For more information on the conversion to objectId, see Converting to an ObjectId.
"bool"
8
For more information on the conversion to boolean, see Converting to a Boolean.
"date"
9
For more information on the conversion to date, see Converting to a Date.
"int"
16
For more information on the conversion to integer, see Converting to an Integer.
"long"
18
For more information on the conversion to long, see Converting to a Long.
"decimal"
19
For more information on the conversion to decimal, see Converting to a Decimal.
- 参考自mongodb官方文档$convert