[英]Making a case-insensitive “like” query using the mongodb driver in Node
I'm looking to make a query like mentioned in the title with an array of data. 我正在寻找一个如标题中提到的带有数据数组的查询。
I have this line working.. 我有这条线在工作..
collection.find({"name": {"$in":[/papa JOhn's/i,"Taco Bell"]}}).toArray(function(err, items) {
However, the data is going to be dynamic and fed into the query as an array 但是,数据将是动态的,并以数组的形式输入到查询中
restaurant_data = [rest1, rest2 .... restn]
I want to essentially have something like 我本质上想要
collection.find({"name": {"$in": /restaurant_data/i }}).toArray(function(err, items) {
let test_data = ['papa john', 'taco bell']
//Get an array of the restaurant names here
collection.find({"name": {"$in": test_data.map(element => {
/element/i
})}}).toArray(function(err, items) {
I got it doing this... Not sure if it's the most efficient 我是这样做的...不确定是否是最有效的
let test_data = ['papa john', 'taco bell']
collection.find({"name": {"$in": test_data.map((element) => {
var regex = new RegExp(".*" + element + ".*");
return regex
})}}).toArray(function(err, items) {
collection.find({"name": {"$in":
restaurant_data.map(e => new RegExp(e, 'i'))
}}).toArray
has better chance to work. 有更好的工作机会。 Note that /bla/i
will match blabla
so 请注意, /bla/i
将与blabla
匹配,因此
collection.find({"name": {"$in": [/bla/i] } })
will match documents with name blabla
Not sure this is what you want or not. 将匹配名称为blabla
文档。不确定这是否是您想要的。
If you're using mongodb 3.2+ I'd recommending you using the property Collation as using Regex might make the queries quite slower, you can use it in both creating indexes as well as querying: 如果您使用的是mongodb 3.2+,则建议您使用归类属性,因为使用Regex可能会使查询变慢,因此您可以在创建索引和查询时都使用它:
db.peeps.createIndex({UserName:-1}, { collation: {locale:'en', caseLevel:false, caseFirst: "off"} )
db.peeps.find({UserName:'bob'}).collation({locale:'en', caseLevel:false, caseFirst: "off"}) // 3 results!
However, as I've faced this problem as well when I tried using collation it made my queries at least 2 times slower so I ended up sticking with inserting lowerCase data in mongodb and then validating and using toLowerCase in the payload fields instead of using Collation. 但是,由于我在尝试使用排序规则时也遇到了此问题,它使查询速度至少慢了2倍,所以我最终坚持在mongodb中插入lowerCase数据,然后在有效负载字段中验证并使用toLowerCase而不是使用排序规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.