如何在 Mongodb 上进行不区分大小写的查询? [英] How do I make case-insensitive queries on Mongodb?

查看:26
本文介绍了如何在 Mongodb 上进行不区分大小写的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var thename = 'Andrew';
db.collection.find({'name':thename});

如何查询不区分大小写?即使安德鲁"我也想找到结果;

How do I query case insensitive? I want to find result even if "andrew";

推荐答案

Chris Fulstow 的解决方案将起作用 (+1),但是,它可能效率不高,尤其是当您的集合非常大时.非根正则表达式(那些不是以 ^ 开头的,它将正则表达式锚定到字符串的开头),以及那些使用 i 标志不区分大小写的将不会使用索引,即使它们存在.

Chris Fulstow's solution will work (+1), however, it may not be efficient, especially if your collection is very large. Non-rooted regular expressions (those not beginning with ^, which anchors the regular expression to the start of the string), and those using the i flag for case insensitivity will not use indexes, even if they exist.

您可能考虑的另一种选择是对数据进行非规范化以存储 name 字段的小写版本,例如作为 name_lower.然后您可以有效地查询(特别是如果它被索引)不区分大小写的完全匹配,例如:

An alternative option you might consider is to denormalize your data to store a lower-case version of the name field, for instance as name_lower. You can then query that efficiently (especially if it is indexed) for case-insensitive exact matches like:

db.collection.find({"name_lower": thename.toLowerCase()})

或者使用前缀匹配(有根的正则表达式)为:

Or with a prefix match (a rooted regular expression) as:

db.collection.find( {"name_lower":
    { $regex: new RegExp("^" + thename.toLowerCase(), "i") } }
);

这两个查询都将使用 name_lower 上的索引.

Both of these queries will use an index on name_lower.

这篇关于如何在 Mongodb 上进行不区分大小写的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆