首先需要注意的是:和我一樣,我是mongoDB的新手,儘管下面給出的答案似乎有效,但可能會有更簡潔/高效的方法來達到相同的結果。
這裏是樣本數據集I構成:
/* 0 */
{
"_id" : ObjectId("54d62ce0e11e084bc1366195"),
"kick_off_date" : ISODate("2005-01-16T10:35:54.985Z"),
"competition_id" : 1,
"home_team_id" : 1,
"away_team_id" : 5,
"home_score" : 1,
"away_score" : 3
}
/* 1 */
{
"_id" : ObjectId("54d62cece11e084bc1366196"),
"kick_off_date" : ISODate("2005-02-16T10:35:54.985Z"),
"competition_id" : 1,
"home_team_id" : 2,
"away_team_id" : 5,
"home_score" : 3,
"away_score" : 1
}
/* 2 */
{
"_id" : ObjectId("54d62cfde11e084bc1366197"),
"kick_off_date" : ISODate("2005-03-16T10:35:54.985Z"),
"competition_id" : 1,
"home_team_id" : 3,
"away_team_id" : 5,
"home_score" : 5,
"away_score" : 0
}
/* 3 */
{
"_id" : ObjectId("54d62d0ce11e084bc1366198"),
"kick_off_date" : ISODate("2005-04-16T10:35:54.985Z"),
"competition_id" : 1,
"home_team_id" : 4,
"away_team_id" : 5,
"home_score" : 0,
"away_score" : 5
}
從這個數據可以看出,目標的差異是:
"_id" : ObjectId("54d62ce0e11e084bc1366195"),
"difference" : -2
"_id" : ObjectId("54d62cece11e084bc1366196"),
"difference" : 2
"_id" : ObjectId("54d62cfde11e084bc1366197"),
"difference" : 5
"_id" : ObjectId("54d62d0ce11e084bc1366198"),
"difference" : -5
因爲在那裏負的差異,只是將這些值一起會給我們總共0
,這是沒用的。因此,查詢必須考慮到這一點,並將負數視爲正數,總數爲14
。然後,平均差異爲:(14/4) = 3.5
因此,這裏是聚集查詢,做這一切:
db.full_time_results.aggregate(
{$match:
{
competition_id: 1,
away_team_id: 5,
kick_off_date: { $gte : ISODate("2005-01-01T00:00:00Z") }
}
},
{$project:
{
away_team_id:1,
difference: {$subtract:["$home_score","$away_score"]}
}
},
{$group:
{
_id:"$away_team_id",
avg_difference: {$avg:
{$cond:
{
if: { $lt: [ "$difference", 0 ] },
then: {$multiply:["$difference", -1]},
else: "$difference"
}
}
}
}
}
)
最後,結果是:
{
"_id" : 5,
"avg_difference" : 3.5
}
你有2個選擇,一個MAP-減少工作或使用聚合管道:http://docs.mongodb.org/manual/tutorial/aggregation-zip-code-data-set/ – reptilicus 2015-02-05 22:37:42
非常感謝,將檢查出來 – 2015-02-06 15:37:51