我在MongoDB中有学生数据,并且使用猫鼬作为orm。
我想用与任何学生字段匹配的搜索参数搜索所有学生。
query = {
find: {
$or: [
{ 'first_name': '/' + req.body.search_text + '/' },
{ 'last_name': '/' + req.body.search_text + '/' },
{ 'email': '/' + req.body.search_text + '/' },
{ 'city': '/' + req.body.search_text + '/' },
]
}
}
但是它没有按预期工作。
答案 0 :(得分:1)
您需要正确检查正则表达式:
下面是查询,该查询将找到:
简单查询:
db.getCollection('test').find({
$or: [
{ email: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} },
{ first_name: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} },
{ last_name: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} },
{ city: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} }
]
})
汇总:
db.getCollection('test').aggregate([{
$match:{
$or: [
{ email: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} },
{ first_name: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} },
{ last_name: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} },
{ city: {'$regex': ".*"+ req.body.search_text +".*", $options:'i'} }
]
}
}])