如何在 MongoDB 中使用 $in
操作符搜索包含待查找元素数组的集合列,并进行不区分大小写(caseInsensitive)
匹配?
如何在 MongoDB 中使用 $in
操作符搜索包含待查找元素数组的集合列,并进行不区分大小写(caseInsensitive)
匹配?
{
name : "...Event A",
fieldX : "aAa"
},
{
name : "...Event B",
fieldX : "Bab"
},
{
name : "...Event C",
fieldX : "ccC"
},
{
name : "...Event D",
fieldX : "dDd"
}
我们希望在数组(optValues)的任何值中包含“fieldX”字段的文档:
var optValues = ['aaa', 'bbb', 'ccc', 'ddd'];
var optRegexp = [];
optValues.forEach(function(opt){
optRegexp.push( new RegExp(opt, "i") );
});
db.collection.find( { fieldX: { $in: optRegexp } } );
这对于任何$all都有效。
希望这能帮到你!
p.s.: 这是我在一个Web应用程序中按标签搜索的解决方案。
Regexp.new(opt, Regexp::IGNORECASE)
代替new RegExp(tag, "i")
即可。 - Flo Woovar optRegexp = optValues.map(value => new RegExp("^" + value + "$", "i");
以便与 { $in: optRegexp }
一起使用。 - j3ffdb.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"]
}
]
{
"first_name":{
"$in":[
{"$regex":"^serina$","$options":"i"},
{"$regex":"^andreW$","$options":"i"}
]
}
}
db.mycollection.find({"first_name":{"$in":[/^serina$/i, /^andreW$/i]}})
const sampleData = [
RegExp("^" + 'girl' + "$", 'i'),
RegExp("^" + 'boy' + "$", 'i')
];
const filerObj = { gender : {$in : sampleData}};
在Java中实现的方法是:
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);
$in
,但它不支持不区分大小写的搜索。{
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"]
}
我的查询
db.event.find(
{ $or: //use $and or $or depends on your needs
[
{ tags : {
$elemMatch : { $regex : '^tag1$', $options : 'i' }
}
},
{ tags : {
$elemMatch : { $regex : '^tag3$', $options : 'i' }
}
}
]
})