我有一个拥有嵌套玩家的团队数据库如下:
{
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值。
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 }
...
}
(球员年龄肯定都在那里)
任何帮助?
答案 0 :(得分:5)
由于players
字段是一个数组,因此尝试使用$players.age
访问其成员时太麻烦了,mongo不知道您要访问的数组的哪个元素。
然后来$unwind
进行救援,它将使数组的每个元素成为字段players
的嵌入元素。
如果您$unwind
使用文档#34;曼联",那么您将拥有类似的内容
{ "_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
可以轻松访问玩家的年龄,因为它是一个嵌入式文档。
最终查询
cursor = db.teams.aggregate([
{ $unwind: "$players" },
{ $group : { _id: "$name", avgAge : { $avg : "$players.age" } } }
]);
答案 1 :(得分:0)
如果您尝试将值存储回文档,则可以简化为:
db.teams.updateMany({}, [{$set: {average: {$avg: "$players.age"}}}])
我不确定这是否是最近的更改,但我正在运行 Mongo 4.4 并且可以正常工作。