經過如此習慣SQL之後,我遇到了mongoDB這個問題。 首先,我正在使用貓鼬。MongoDB查詢結果中的自定義字段
現在,問題所在。我有一個名爲User
的集合。
var UserSchema = new Schema ({
id : ObjectId,
name : {type : String, trim : true, required : true},
email: {type:String, trim:true, required: true, index: { unique: true }},
password: {type:String, required: true, set: passwordToMD5},
age: {type:Number, min: 18, required: true, default: 18},
gender: {type: Number, default:0, required: true},
height: {type: Number, default:180, min: 140, max: 220},
_eye_color: {type: ObjectId, default: null},
location: {
lon: {type: Number, default: 0},
lat: {type: Number, default: 0}
},
status: {type:Number, required: true, default:0}
},{
toObject: { virtuals: true },
toJSON: { virtuals: true },
collection:"user"});
現在我需要從這個集合中選擇所有用戶和特殊attribude排序他們(說「等級」)。這個排名與一定的邏輯從點取決於他們的距離計算,年齡與特定的年齡,等於是現在比較...
我不知道如何選擇這個級別,然後用它的排序?我試圖使用虛擬化,他們很方便地計算其他信息,但不幸的是,不可能通過虛擬字段對find()
結果進行排序。 當然我可以在虛擬中計算這個等級,然後選擇所有記錄,然後在回調中做一些javascript。但是,在這種情況下,我選擇的所有用戶,然後進行排序,然後限制,JavaScript部分可能要花很長時間...... 我想用的MapReduce,但我不知道它會做我想做的。 有人可以給我一個提示,如果我的任務可以做mongoDB/mongoose?
編輯1
我也曾嘗試使用聚合框架,並在第一次似乎與$project
能力的最佳解決方案。但是,當我需要進行排名計算時,我發現聚合不支持很多數學函數,如sin
,cos
和sqrt
。而且在投影中也不可能使用預先定義的通常的javascript函數。我的意思是,函數被調用,但我無法將當前記錄字段傳遞給它。
{$project: {
distance_from_user: mUtils.getDistance(point, this.location)
}
函數裏面的第二個attr是「undefined」。
所以我想這是不可能做我的排名計算與聚合框架。
EDIT 2 好吧,我知道每個人都告訴我不要使用MapReduce的,因爲它不利於實時查詢,但我不能用聚集,我想我會嘗試的MapReduce。所以我們說我有這個地圖縮小。
function map() {
emit(1, // Or put a GROUP BY key here
{name: this.name, // the field you want stats for
age: this.age,
lat: this.location.lat,
lon: this.location.lon,
distance:0,
rank:0
});
}
function reduce(key, values) {
return val;
}
function finalize(key, value){
return value;
}
var command = {'mapreduce': "user", 'map': map.toString(), 'reduce': reduce.toString(), query:{$and: [{gender: user_params.gender}, {_id: {$ne: current_user_id}}]}, 'out': {inline:1}};
mongoose.connection.db.executeDbCommand(command, function(error, result){
if(error) {
log(error);
return;
}
log(result);
return;
});
我應該寫在減少(或可能改變地圖)來計算每個用戶的排名?
您不應該使用mapreduce進行'實時'查詢。看看聚合框架http://docs.mongodb.org/manual/applications/aggregation/ – Alex
我已經嘗試過聚合,但是在聚合框架中,不可能使用我需要的功能進行排名計算。例如,沒有'sqrt()','sin()','cos()'等。 – ArVan