当前位置:  开发笔记 > 编程语言 > 正文

MongoDB - 计算对象属性的嵌套数组的平均值

如何解决《MongoDB-计算对象属性的嵌套数组的平均值》经验,为你挑选了1个好方法。

我有一个拥有嵌套玩家的团队数据库如下:

{
 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 }
  ...
}

(球员年龄肯定都在那里)

有帮助吗?



1> somallg..:

由于该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" } } }
]);

推荐阅读
路人甲
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有