Regex只能在所匹配的字段具有stirng值时匹配,但num在您的示例中是一个数字。
它在Mongodb文档中这样说:
https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex
但是,有一个使用“$where”的解决方案,您可以在其中执行Javascript以返回布尔值。
db.collection.find({
$where: "/45/.test(this.num) && this.name==='yo'"
})
我在蒙古人的地盘上试过。
试试看:
https://mongoplayground.net/p/8E9kGt5moAO
https://docs.mongodb.com/manual/reference/operator/query/where/#where
还有一种方法可以在不使用$where的情况下完成此操作(在MongoDb 4.2中):
db.collection.find({
$expr: {
$and: [
{
$regexMatch: {
input: {
$toString: "$num"
},
regex: "45"
}
},
{
$gte: [
"$time",
12350
]
},
{
$lt: [
"$time",
12400
]
}
]
}
})