我有一个users
具有类型的位置字段的集合String
。我想沿着文档传递一个分数字段,该字段显示文档的位置是否与文本“Austin”相似。例如记录的位置是德克萨斯州奥斯汀,我希望它与Austin。我以为可以使用$regex为了这。
我写了这个聚合:
$project: {
score: {
$cond:
if: {
$regex: {'$location': /Austin/}
},
then: 1,
else: 0
}
},
location: 1,
firstName: 1,
lastName: 1
}
但我得到的是:
{
"name": "MongoError",
"errmsg": "exception: invalid operator '$regex'",
"code": 15999,
"ok": 0
}
我知道这是一个老问题,但从 4.2 版开始你可以使用$正则表达式匹配 https://docs.mongodb.com/manual/reference/operator/aggregation/regexMatch/.
您可以使用此阶段:
{
$project: {
score: {
$cond: {
if: {
$regexMatch: {
input: "$location",
regex: "Austin"
}
},
then: 1,
else: 0
}
},
location: 1,
firstName: 1,
lastName: 1
}
}
Example here https://mongoplayground.net/p/zhZPRA8wR0c
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)