我有一个“匹配”类型的文档集合:
{
"_id": { "$oid" : "51b6eab8cd794eb62bb3e131" },
"_player1": { "_id": "2" },
"_player2": { "_id": "6" },
"_result": { "_sets": [ [ 6, 3 ], [ 6, 3 ], [ 5, 6 ], [ 6, 5 ] ]
},
{
"_id": { "$oid" : "51b6eab8cd794eb62bb3341" },
"_player1": { "_id": "2" },
"_player2": { "_id": "3" },
"_result": { "_sets": [ [ 6, 3 ], [ 6, 7 ], [ 7, 6 ], [ 6, 5 ] ]
},
{
"_id": { "$oid" : "51b6eab8cd794eb62bb3341" },
"_player1": { "_id": "2" },
"_player2": { "_id": "4" },
"_result": { "_sets": [ [ 6, 1 ], [ 1, 6 ], [ 6, 2 ], [ 6, 5 ] ]
}
我需要计算具有给定 ID(例如 2)的玩家的获胜、平局和失败的比赛数量以及获胜和失去的点数
我已经尝试了这两个选项,但没有一个有效(没有提供任何结果)
选项1:
matches.group({
"initial": {
"number_of_points_won": 0,
"number_of_points_lost": 0,
"number_of_matches_won": 0,
"number_of_matches_tied": 0,
"number_of_matches_lost": 0
},
"reduce": function(obj, prev) {
if(obj._result!=null && obj._result._sets!=null && obj._result._sets instanceof Array){
if(obj._result._sets.lenght>0){
current= { number_of_points_won: 0, number_of_points_lost: 0 };
for (var idx = 0; idx < obj._sets.length; idx++) {
if(obj._sets[idx][0] > obj._sets[idx][1]){
current.number_of_points_won++;
prev.number_of_points_won++;
}else if(obj._sets[idx][0] < obj._sets[idx][1]){
current.number_of_points_lost++;
prev.number_of_points_lost++;
}
}
if(current.number_of_points_won > current.number_of_points_lost){
prev.number_of_matches_won++;
}else if(current.number_of_points_won < current.number_of_points_lost){
prev.number_of_matches_lost++;
}else {
prev.number_of_matches_tied++;
}
}
}
},
"cond": {
"matches._player1._id": "2"
}
});
选项 2:
db.matches.mapReduce(
function Map() {
var key = this._player1._id;
emit(key, {"data":[{"_sets" : this._result._sets}]});
},
function Reduce(key, values) {
var reduced = {"data":[]};
for (var i in values)
{
var inter = values[i];
for (var j in inter.data) {
reduced.data.push(inter.data[j]);
}
}
return reduced;
}
function Finalize(key, reduced) {
var statistics = {"number_of_points_won": 0, "number_of_points_lost": 0, "number_of_matches_won": 0, "number_of_matches_tied":0, "number_of_matches_lost":0};
current = { number_of_points_won: 0, number_of_points_lost: 0 };
for (var set in reduced.data) {
for (var idx = 0; idx < set.length; idx++) {
if(set[idx][0] > set[idx][1]){
current.number_of_points_won++;
statistics.number_of_points_won++;
}else if(set[idx][0] < set[idx][1]){
current.number_of_points_lost++;
statistics.number_of_points_lost++;
}
}
if(current.number_of_points_won > current.number_of_points_lost){
statistics.number_of_matches_won++;
}else if(current.number_of_points_won < current.number_of_points_lost){
statistics.number_of_matches_lost++;
}else {
statistics.number_of_matches_tied++;
}
}
return statistics;
},
query : { "$where" : "{\"player1._id\" : { \"$e\" : \"2\" }}" }
);
任何帮助,请。我是 mongo 的新手。