MongoDB-计算对象属性嵌套数组的平均值 [英] MongoDB - calculating average of nested array of objects' attributes
问题描述
我有一个包含嵌套玩家的球队的数据库,如下所示:
I have a database of teams with nested players as below:
{
team_id: "eng1",
date_founded: new Date("Oct 04, 1896"),
league: "Premier League",
points: 62,
name: "Manchester United",
players: [ { p_id: "Rooney", goal: 85, caps: 125, age: 28 },
{ p_id: "Scholes", goal: 15, caps: 225, age: 28 },
{ p_id: "Giggs", goal: 45, caps: 359, age: 38 } ]
}
我正在尝试计算每支球队的平均年龄(所有球员年龄的平均值),但是我无法正确访问$ player.age值.
I'm trying to calculate the average age of each team (the average of all players' ages), however I can't access the $player.age values correctly.
cursor = db.teams.aggregate({
$group : { _id: "$name", avgAge : {
$avg : "$players.age" }
}
});
这只会返回以下内容:
{
{ "_id": "AC Milan", avgAge: 0 },
{ "_id": "Barcelona", avgAge: 0 }
{ "_id": "Real Madrid", avgAge: 0 }
...
}
(所有年龄段的球员肯定都在那儿)
(The players ages are all definitely there)
有帮助吗?
推荐答案
由于players
字段是一个数组,因此尝试使用$players.age
访问其成员太混乱了,mongo不知道该数组的哪个元素您要访问.
然后$unwind
进行救援,它将使数组的每个元素成为字段players
的嵌入元素.
如果您对文档曼彻斯特联队"进行$unwind
,您将拥有类似的内容
Since the players
field is an array, trying to access its member with $players.age
is too confusing, mongo doesn't know which element of the array you want to access.
Then come $unwind
to the rescue, it will make each element of the array to become the embedded element of the field players
.
If you do $unwind
with the document "Manchester United", you will have something like this
{ "_id" : ObjectId("5666fbbd755e59eab7a3e05e"), "team_id" : "eng1", "date_founded" : ISODate("1896-10-03T17:00:00Z"), "league" : "Premier League", "points" : 62, "name" : "Manchester United", "players" : { "p_id" : "Rooney", "goal" : 85, "caps" : 125, "age" : 28 } }
{ "_id" : ObjectId("5666fbbd755e59eab7a3e05e"), "team_id" : "eng1", "date_founded" : ISODate("1896-10-03T17:00:00Z"), "league" : "Premier League", "points" : 62, "name" : "Manchester United", "players" : { "p_id" : "Scholes", "goal" : 15, "caps" : 225, "age" : 28 } }
{ "_id" : ObjectId("5666fbbd755e59eab7a3e05e"), "team_id" : "eng1", "date_founded" : ISODate("1896-10-03T17:00:00Z"), "league" : "Premier League", "points" : 62, "name" : "Manchester United", "players" : { "p_id" : "Giggs", "goal" : 45, "caps" : 359, "age" : 38 } }`
上述文档的字段players
具有3个元素,因此您将拥有
与原始文档具有相同属性的3个文档,但数组中的元素已上移为players
的嵌入式文档.
然后,使用$players.age
即可轻松了解播放器的年龄,因为它是嵌入式文档.
The field players
of the above document have 3 element, so you will have
3 documents with same property like the original document, but the element in the array have moved up to be come embedded document of players
.
Then access to the age of a player is easy with $players.age
because its an embedded document.
最终查询
cursor = db.teams.aggregate([
{ $unwind: "$players" },
{ $group : { _id: "$name", avgAge : { $avg : "$players.age" } } }
]);
这篇关于MongoDB-计算对象属性嵌套数组的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!