让 mongo 的聚合管道案例变得麻木不仁



我正在使用mongo的聚合管道对集合进行搜索。

下面是我的过滤条件:

filter := bson.D{
{"$project", bson.D{
{"names", bson.D{
{"$filter", bson.D{
{"input", "$names"},
{"as", "names"},
{"cond", bson.D{
{"$and", bson.A{
bson.D{{"$eq", bson.A{"$$names.firstname", "John"}}},
bson.D{{"$eq", bson.A{"$$names.lastname", "Doe"}}},
}},
}},
}},
}},
}},
}

这个过滤器工作得很好,但是区分大小写。如果传递的是john而不是John,则返回0个文档。如何使firstnamelastname对大小写不敏感?

您可以这样使用$regexMatch$filter:

请注意,我使用Regex^name$只匹配单词,您可以使用您想要的Regex,但使用选项i, Regex是不区分大小写的。

db.collection.aggregate([
{
"$project": {
"names": {
"$filter": {
"input": "$names",
"as": "names",
"cond": {
"$and": [
{
"$regexMatch": {
"input": "$$names.firstname",
"regex": "^John$",
"options": "i"
}
},
{
"$regexMatch": {
"input": "$$names.lastname",
"regex": "^Doe$",
"options": "i"
}
}
]
}
}
}
}
}
])

例子

最新更新