【问题标题】:sorting regex find mongodb mongoose排序正则表达式找到 mongodb mongoose
【发布时间】:2017-12-22 09:23:40
【问题描述】:

mongodb 中的正则表达式查找更像是过滤器而不是搜索。有没有办法根据正则表达式对结果进行排序?

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

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

此外,性能不是问题。

【问题讨论】:

  • “根据正则表达式对结果进行排序”是什么意思?更新您的问题以包含特定示例将非常有帮助。

标签: mongodb mongoose


【解决方案1】:

$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,排名第一

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    相关资源
    最近更新 更多