Reputation: 3
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) {
Upvotes: 0
Views: 1172
Reputation: 192
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:
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.
Upvotes: 0
Reputation: 10327
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
collection.find({"name": {"$in": [/bla/i] } })
will match documents with name blabla
Not sure this is what you want or not.
Upvotes: 1