Reputation: 3950
How to search a column in a collection in mongodb with $in
which includes an array of elements for search and also caseInsensitive
matching of those elements in the column ?
Upvotes: 29
Views: 22573
Reputation: 22659
You can use $elemMatch with regular expressions search, e.g. let's search for "blue" color in the following collection:
db.items.save({
name : 'a toy',
colors : ['red', 'BLUE']
})
> ok
db.items.find({
'colors': {
$elemMatch: {
$regex: 'blue',
$options: 'i'
}
}
})
>[
{
"name": "someitem",
"_id": { "$oid": "4fbb7809cc93742e0d073aef"},
"colors": ["red", "BLUE"]
}
]
Upvotes: 15
Reputation: 84
This works for me perfectly.
From code we can create custom query like this:
{
"first_name":{
"$in":[
{"$regex":"^serina$","$options":"i"},
{"$regex":"^andreW$","$options":"i"}
]
}
}
This will transform to following in mongo after query:
db.mycollection.find({"first_name":{"$in":[/^serina$/i, /^andreW$/i]}})
Same for "$nin".
Upvotes: 4
Reputation: 21
The way to do it in Java is:
List<String> nameList = Arrays.asList(name.split(PATTERN));
List<Pattern> regexList = new ArrayList<>();
for(String name: nameList) {
regexList.add(Pattern.compile(name , Pattern.CASE_INSENSITIVE));
}
criteria.where("Reference_Path").in(regexList);
Upvotes: 1
Reputation: 4558
This is pretty simple
const sampleData = [
RegExp("^" + 'girl' + "$", 'i'),
RegExp("^" + 'boy' + "$", 'i')
];
const filerObj = { gender : {$in : sampleData}};
Upvotes: 2
Reputation: 978
Use $in with the match being case insensitive:
Data example:
{
name : "...Event A",
fieldX : "aAa"
},
{
name : "...Event B",
fieldX : "Bab"
},
{
name : "...Event C",
fieldX : "ccC"
},
{
name : "...Event D",
fieldX : "dDd"
}
And we want documents were "fieldX" is contained in any value of the array (optValues):
var optValues = ['aaa', 'bbb', 'ccc', 'ddd'];
var optRegexp = [];
optValues.forEach(function(opt){
optRegexp.push( new RegExp(opt, "i") );
});
db.collection.find( { fieldX: { $in: optRegexp } } );
This works for $all either.
I hope this helps!
p.s.: This was my solution to search by tags in a web application.
Upvotes: 18
Reputation: 6173
Here is my case insensitive search (query) with multiple condition (regex) from data of array, I've used $in
but it doesn't support case insensitive search.
Example Data
{
name : "...Event A",
tags : ["tag1", "tag2", "tag3", "tag4]
},
{
name : "...Event B",
tags : ["tag3", "tag2"]
},
{
name : "...Event C",
tags : ["tag1", "tag4"]
},
{
name : "...Event D",
tags : ["tag2", "tag4"]
}
My query
db.event.find(
{ $or: //use $and or $or depends on your needs
[
{ tags : {
$elemMatch : { $regex : '^tag1$', $options : 'i' }
}
},
{ tags : {
$elemMatch : { $regex : '^tag3$', $options : 'i' }
}
}
]
})
Upvotes: 0