$regex 仅用于字段类型 String,不适用于其他类型
让我们考虑使用正则表达式的小例子
//让用户模型如下
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
Name:String,
Age:Number,
Sex:Boolean,
EmailID:String,
PhoneNumber:String,
Description:String,
created_at:Date,
updated_at:Date
});
module.exports = mongoose.model('UserSchema', UserSchema);
您使用 $regex 运算符和 $options 进行多重搜索的 mongodb 查询将如下所示
var toSearch = req.body.searchvalue;
var query = {
$or:[
{
"Name":{
$regex:toSearch,
$options:"i" //it will match both upper case and lower case
}
},
{
"EmailID":{
$regex:toSearch,
$options:"i" //it will match both upper case and lower case
}
},
{
"PhoneNumber":{
$regex:toSearch,
$options:"i" //it will match both upper case and lower case
}
},{
"Description":{
$regex:toSearch,
$options:"i" //it will match both upper case and lower case
}
}
]
}
//Important point to remember we cannot use $regex for age,sex,created_at,updated_at because this field are not String
UserSchema.find(query).toArray(function (err,SearchData) {
if(!err){
//perform your operations
}
}) ;
这可能对您有所帮助,最好在 mongodb 中创建搜索引擎。它仅次于 Elastic Search,排名第一