我有一个充满投注市场的集合markets
。我在集合中的数据如下所示:
{ "team" : "Milan", "back" : 1.0, "lay" : 1.0, "btotal" : 7.0, "ltotal" : 6.0 },
{ "team" : "Chelsea", "back" : 1.0, "lay" : 1.0, "btotal" : 1.0, "ltotal" : 1.0 },
{ "team" : "Arsenal", "back" : 1.0, "lay" : 1.0, "btotal" : 1.0, "ltotal" : 1.0 },
{ "team" : "Milan", "back" : 3.0, "lay" : 3.0, "btotal" : 1.0, "ltotal" : 18.0 }
我想将我的数据显示为唯一名称列表,该行的最高btotal
和相应的back
赔率,最高ltotal
及其对应的{{1}赔率。
从上面的例子中,返回的数据应为:
lay
这是第一次出现{"team":"Milan", "back":1.0, "lay":3.0, "btotal":7.0, "ltotal":18.0},
{"team":"Chelsea", "back":1.0, "lay":1.0, "btotal":1.0, "ltotal":1.0},
{"team":"Arsenal", "back":1.0, "lay":1.0, "btotal":1.0, "ltotal":1.0}
时btotal
中的输出大于第二次出现的输出,因此返回"team":"Milan"
赔率,{{1} } {第二次出现的back
高于第一次,因此返回该行的ltotal
赔率。
有关如何在Mongo或Mongoose中构建此查询的任何想法将不胜感激。
答案 0 :(得分:0)
你能使用mapReduce吗?
地图功能
var map = function() {
emit(this.team, this);
}
和reduce函数:
var reduce = function(key, values) {
var res = values[0];
for (var i = 1; i < values.length; i++) {
if (values[i].btotal > res.btotal) {
res.back = values[i].back;
res.btotal = values[i].btotal;
}
if (values[i].ltotal > res.ltotal) {
res.lay = values[i].lay;
res.ltotal = values[i].ltotal;
}
}
return res;
}
执行map-reduce操作:
db.markets.mapReduce(map, reduce, {out: "mpmarkets"});
使用$ project(聚合)生成预期输出:
cursor = db.mpmarkets.aggregate([{
$project: {_id:0,
team: "$_id",
back: "$value.back",
lay: "$value.lay",
btotal: "$value.btotal",
ltotal: "$value.ltotal"} },
{$sort: {team: -1}
}]);
打印结果:
while ( cursor.hasNext() ) {
printjson( cursor.next() );
}
结果:
{ "team" : "Milan", "back" : 1, "lay" : 3, "btotal" : 7, "ltotal" : 18 }
{ "team" : "Chelsea", "back" : 1, "lay" : 1, "btotal" : 1, "ltotal" : 1 }
{ "team" : "Arsenal", "back" : 1, "lay" : 1, "btotal" : 1, "ltotal" : 1 }