You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置MongoDB aggregation pipeline查询为大小写不敏感

解决方案

方法1:使用$toLower/$toUpper运算符实现大小写不敏感比较

这是通用度最高的实现方式,不需要额外配置索引,直接修改过滤逻辑,将比较的两个值统一转为小写(或大写)后再匹配即可,修改后的代码如下:

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{
                                bson.D{{"$toLower", "$$names.firstname"}}, 
                                bson.D{{"$toLower", "John"}}},
                            }},
                            bson.D{{"$eq", bson.A{
                                bson.D{{"$toLower", "$$names.lastname"}}, 
                                bson.D{{"$toLower", "Doe"}}},
                            }},
                        }},
                    }},
                }},
            }},
        }},
    }

注意:你传入的搜索值(比如john)也会被统一转成小写,不管传入的是大写、小写还是混合大小写都可以正常匹配。

方法2:使用Collation(推荐大数据量场景)

如果你使用的MongoDB版本 >= 3.4,更推荐使用Collation实现大小写不敏感,性能比逐字段转大小写更高,尤其是在对应字段建有适配对应Collation的索引时查询效率优势明显。
你不需要修改原始过滤逻辑,只需要在执行聚合管道的时候额外指定Collation参数即可,Go语言中调用聚合的示例代码如下:

// 定义collation配置,strength=2表示忽略大小写和重音差异
collation := options.Collation{
    Locale:   "en",
    Strength: 2,
}
// 执行聚合时传入collation参数
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{filter}, options.Aggregate().SetCollation(&collation))

内容的提问来源于stack exchange,提问作者shekwo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:57:04