使用聚合框架,您“理想地”希望使用$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 } }