英文:
Making mongo's aggregation pipeline case insenstive
问题
我正在使用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个文档。如何使firstname
和lastname
不区分大小写?
英文:
I am using mongo's aggregation pipeline to do a search on a collection.
Here is my filter condition:
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"}}},
}},
}},
}},
}},
}},
}
This filter works well but it is case sensitive. If pass john
instead of John
, it returns 0 documents. How do I make firstname
and lastname
case insenstive?
答案1
得分: 1
你可以在 $filter
中使用 $regexMatch
,像这样:
请注意,我使用了正则表达式 ^name$
来匹配单词,你可以使用你想要的正则表达式,但是使用选项 i
时,正则表达式是不区分大小写的。
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"
}
}
]
}
}
}
}
}
])
示例可以在这里找到。
英文:
You can use $regexMatch
into $filter
like this:
Note that I've used Regex ^name$
to match only the word, you can use the regex you want, but with option i
, the regex is case insensitive.
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"
}
}
]
}
}
}
}
}
])
Example here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论