在mongo中执行优先级查询

2024-03-20

样本文件:

{"name":"John", "age":35, "address":".....",.....}
  1. join_month=3 的员工优先级为 1
  2. 地址包含字符串“Avenue”的员工优先级为 2
  3. 地址包含字符串“Street”的员工优先级为 3
  4. 地址包含字符串“Road”的员工优先级为 4

到目前为止,我正处于这个阶段:

db.collection.aggregate([
    { "$match": { 
        "$or": [ 
            { "join_month": 3 }, 
            { "address": /.*Avenue.*/i }, 
            { "address": /.*Street.*/i }, 
            { "address": /.*Road.*/i }
        ] 
    }}, 
    { "$project": { 
        "name": 1, 
        "age": 1,
        "_id": 0, 
        "priority": { ?????????? } 
    }}, 
    { "$sort":  { "priority": 1 } }
])

我被困在优先领域。我应该在那里放什么?


使用聚合框架,您“理想地”希望使用$regex https://docs.mongodb.org/manual/reference/operator/query/regex/过滤器内$cond https://docs.mongodb.org/manual/reference/operator/aggregation/cond/#exp._S_cond中的逻辑运算符$project https://docs.mongodb.org/manual/reference/operator/aggregation/project/#pipe._S_project管道步骤,但不幸的是 MongoDB 还不支持这一点。 目前有此开放的 JIRA 票证使用 $regex 的 $project 过滤器 https://jira.mongodb.org/browse/SERVER-11947

但是,一种解决方法(尽管不是性能方面的最佳解决方案)是使用map-reduce https://docs.mongodb.org/manual/core/map-reduce/。考虑填充测试集合:

db.test.insert([
    { _id: 0, "join_month": 12, "address": "33 Point Avenue", "name": "John", "age":35 },
    { _id: 1, "join_month": 10, "address": "2A Broad Street, Surbub", "name": "Jane", "age":21 },
    { _id: 2, "join_month": 3, "address": "127 Umpstreeten Road, Surbub", "name": "Alan", "age":63 },
    { _id: 3, "join_month": 3, "address": "127 Umpstreeten Road, Surbub", "name": "Louise", "age":30 }
])

将地图函数定义为:

var mapper = function() {
    var priority;
    if (this.join_month==3){
        priority = 1;
    }
    else if (this.address.match(/Avenue/i)){
        priority = 2;
    }
    else if (this.address.match(/Street/i)){
        priority = 3;
    }
    else if (this.address.match(/Road/i)){
        priority = 4;
    }
    else {
        priority = 99;
    }

    var value = {
        "name": this.name, 
        "age": this.age,
        "priority": priority
    };
    emit( this._id, value );        
};

归约函数如下:

var reducer = function() { };

然后对测试集合运行mapduce操作并将结果存储在集合中mr_result

db.test.mapReduce(mapper, reducer, {
    "out": 'mr_result'
    "query": {
        "$or": [ 
            { "join_month": 3 }, 
            { "address": /.*Avenue.*/i }, 
            { "address": /.*Street.*/i }, 
            { "address": /.*Road.*/i }
        ] 
    }
})

查询结果集合:

db.mr_result.find().sort({ "priority": 1})

样本输出

{ "_id" : 2, "value" : { "name" : "Alan", "age" : 63, "priority" : 1 } }
{ "_id" : 3, "value" : { "name" : "Louise", "age" : 30, "priority" : 1 } }
{ "_id" : 0, "value" : { "name" : "John", "age" : 35, "priority" : 2 } }
{ "_id" : 1, "value" : { "name" : "Jane", "age" : 21, "priority" : 3 } }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在mongo中执行优先级查询 的相关文章

随机推荐