【问题标题】:Find the average value, MongoDB求平均值,MongoDB
【发布时间】:2022-01-19 15:31:09
【问题描述】:

我需要找出每个恐怖系列的平均长度。

我有两个系列系列和书籍,书籍属于系列并且有字段长度,系列有字段“流派”。

系列

{
  "_id": "61179c8d43400f31df195223",
  "name": "serie1",
   "book genre": Horror
},
{
  "_id": "61179c8d43400f31df195223",
  "name": "serie2",
   "book genre": Romance
},
{
  "_id": "61179c8d43400f31df195223",
  "name": "serie3",
   "book genre": Horror
},
{
  "_id": "61179c8d43400f31df195223",
  "name": "serie4",
   "book genre": Horror
},

书籍

{
  "_id": "61179c8d43400f31df195223",
  "name": "book1",
   "lenght": 100,
   "serie": "serie1"
},
{
  "_id": "61179c8d43400f31df195223",
  "name": "book2",
   "lenght": 10,
   "serie": "serie3"
},
{
  "_id": "61179c8d43400f31df195223",
  "name": "book3",
   "lenght": 900,
   "serie": "serie3"
},
{
  "_id": "61179c8d43400f31df195223",
  "name": "book4",
   "lenght": 300,
   "serie": "serie1"
},

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您可以使用非常标准的聚合来做到这一点,这里我使用$lookup$avg$map 来实现最终结果:

    db.series.aggregate([
      {
        $lookup: {
          from: "books",
          localField: "name",
          foreignField: "serie",
          as: "books"
        }
      },
      {
        $project: {
          _id: 1,
          name: 1,
          "book genre": 1,
          avg: {
            "$ifNull": [
              {
                $avg: {
                  $map: {
                    input: "$books",
                    in: "$$this.lenght"
                  }
                }
              },
              0
            ]
          }
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

    • 我需要找到所有带有genre="Horror"的专辑的平均长度
    • 所以我必须把恐怖专辑的所有长度加起来,然后除以它们的数量
    • 我们可以总结所有恐怖书籍的长度,并根据恐怖类型划分系列的数量
    • 是的,你也可以分组并使用'$avg'操作符,他会为你做这些
    【解决方案2】:

    查询

    • 查找每种类型的平均值,例如所有恐怖电影的平均长度
    • 按流派分组
    • 查找长度
    • 求平均值

    *汤姆斯的回答是每个系列的平均值,如果你不想要这个,也许你想要这个?我不知道。如果您将预期的输出发送给我们会有所帮助,我认为您也想要 Tom 所做的。

    Test code here

    series.aggregate(
    [{"$group":{"_id":"$book genre", "series":{"$push":"$name"}}},
     {"$lookup":
      {"from":"books",
       "localField":"series",
       "foreignField":"serie",
       "as":"series"}},
     {"$set": 
      {"book genre":"$_id",
       "_id":"$$REMOVE",
       "avgTime":{"$avg":"$series.lenght"}}}])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2014-02-13
      • 1970-01-01
      相关资源
      最近更新 更多