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

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

问题描述

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

如何查询不区分大小写?我想要查找结果,即使andrew;

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

推荐答案

Chris Fulstow的解决方案将工作不高效,尤其是如果你的收藏非常大。非根的正则表达式(那些不以 ^ 开头的正则表达式,它将正则表达式锚定到字符串的开头)和那些使用 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.

您可能考虑的一个替代选项是反正规化您的数据以存储较低-c版本的名称字段,例如 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()})

正则表达式)为:

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

这两个查询都将使用 name_lower

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

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