我有一个工作的Mongo查询需要翻译成Ruby:
var reducer = function(current, result){
result.loginsCount++;
result.lastLoginTs = Math.max(result.lastLoginTs, current.timeStamp);
}
var finalizer = function(result){
result.lastLoginDate = new Date(result.lastLoginTs).toISOString().split('T')[0];
}
db.audit_log.group({
key : {user : true},
cond : {events : { $elemMatch : { action : 'LOGIN_SUCCESS'}}},
initial : {lastLoginTs : -1, loginsCount : 0},
reduce : reducer,
finalize : finalizer
})
我在Ruby中遇到了几个难点。我并不是真的熟悉Mongo,而且我不确定要作为方法调用的参数传递什么。在连接到数据库和名为audit_log的集合之后,这是我最好的猜测:
audit_log.group({
"key" => {"user" => "true"},
"cond" => {"events" => { "$elemMatch" => { "action" => "LOGIN_SUCCESS"}}},
"initial" => {"lastLoginTs" => -1, "loginsCount" => 0},
"reduce" => "function(current, result){result.loginsCount += 1}",
"finalize" => "function(result){ result.lastLoginDate = new Date(result.lastLoginTs).toISOString().split('T')[0]; }
})
或类似的东西。我尝试使用Mongo文档使用更简单的聚合操作,但我也无法使用它。我只能得到非常简单的查询来返回结果。这些键(key,cond,initial等)是否必要,或仅适用于JavaScript?
答案 0 :(得分:0)
这是函数最终使用1.10.0 Mongo gem的形式:
@db.collection("audit_log").group(
[:user, :events],
{'events' => { '$elemMatch' => { 'action' => 'LOGIN_SUCCESS' }}},
{ 'lastLoginTs' => -1, 'loginsCount' => 0 },
"function(current, result){ result.loginsCount++; result.lastLoginTs = Math.max(result.lastLoginTs, current.timeStamp);}",
"function(result){ result.lastLoginDate = new Date(result.lastLoginTs).toISOString().split('T')[0];}"
)
使用Mongo Driver,您可以不用键:"键"," cond"," initial"," reduce", "完成"并简单地传递相应的值。