我有一个拥有嵌套玩家的团队数据库如下:
{ 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 } ... }
(球员年龄肯定都在那里)
有帮助吗?
由于该players
字段是一个数组,尝试访问其成员$players.age
太混乱,mongo不知道您要访问的数组的哪个元素.然后来$unwind
救援,它将使数组的每个元素成为该字段的嵌入元素players
.如果您$unwind
使用"曼联"文档,您将拥有类似的内容
{ "_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" } } } ]);