排序正则表达式找到mongodb猫鼬

时间:2017-07-17 18:17:00

标签: mongodb mongoose

mongodb中的正则表达式更像是过滤器而不是搜索。无论如何根据正则表达式对结果进行排序?

P.S:我知道MongoDB有全文搜索功能,但我正在寻找一种即使输入部分单词也能得到结果的解决方案。

此外,我知道存在将MongoDB与Elastic Search连接起来的解决方案,但我正在寻找一种不需要托管其他服务的简单解决方案。

此外,性能不是问题。

1 个答案:

答案 0 :(得分:0)

$ regex仅用于字段类型String.It不能与其他类型一起使用

让我们考虑使用正则表达式运算符

的小例子

//让用户模型如下

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运算符进行多搜索的mongodb查询和多搜索的$ options将如下所示

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中创建搜索引擎。它是下一个对弹性搜索有效的第1个