【问题标题】:How can I get an AVG value in MongoDB from the group it has returned?如何从它返回的组中获取 MongoDB 中的 AVG 值?
【发布时间】:2015-08-28 22:37:58
【问题描述】:

嗯,我的 MongoDB 数据库中有以下集合:

{
  "_id": 1,
  "departamento_id": 1,
  "nome": "PRODUTO01",
  "valor": 10.511608123779297
}

所以,考虑到集合中的 所有 文档,我很傻,我做了以下操作以从 valor 字段中获取 平均 值:

db.produto.aggregate({
  "$group": {
    "_id": null,
    "avgValor": {
      "$avg": "$valor"
    }
  }
})

这有以下回报:

{
  "_id": null,
  "avgValor": 50.39681773098588
}

问题是,我需要在另一个查询中使用“avgValor”字段中的值。因此,我创建了一个变量并尝试将创建的组的结果存储在其中。问题是,当我在控制台中输入 first 时间的变量名时,它会产生奇迹,但是当我在 second 时间输入变量名时,MongoDB shell 什么也不返回.看看吧:

> db.produto.aggregate({"$group": {"_id": null, "avgValor": {"$avg": "$valor"}}})
{ "_id" : null, "avgValor" : 50.39681773098588 }
> var docMedia = db.produto.aggregate({"$group": {"_id": null, "avgValor": {"$avg": "$valor"}}})
> docMedia
{ "_id" : null, "avgValor" : 50.39681773098588 }
> docMedia
> docMedia
> docMedia
> docMedia

或者如果我在查询中使用变量,系统会返回错误。看看吧:

> var docMedia = db.produto.aggregate({"$group": {"_id": null, "avgValor": {"$avg": "$valor"}}})
> db.produto.find({valor: {$lte: docMedia.avgValor}})
Error: error: {
    "$err" : "Can't canonicalize query: BadValue cannot compare to undefined",
    "code" : 17287
}

这里会发生什么?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    在 shell 中,aggregate 返回一个游标对象,而不是结果文档本身。当您在 shell 中评估游标对象时,shell 会对其进行迭代,从而耗尽游标。这就是为什么当你第二次评估它时它什么也不返回。

    相反,在aggregate 的结果上调用toArray() 以将结果作为一个数组获取,您可以更轻松地使用。

    var results = db.produto.aggregate({
      "$group": {
        "_id": null,
        "avgValor": {
          "$avg": "$valor"
        }
      }
    }).toArray();
    var avgValor = results[0].avgValor;
    

    或者在这种情况下,null 上的 $group 确保只有一个结果,您只需在光标上调用 next() 即可获得一个结果文档:

    var result = db.produto.aggregate({
      "$group": {
        "_id": null,
        "avgValor": {
          "$avg": "$valor"
        }
      }
    }).next();
    var avgValor = result.avgValor;
    

    【讨论】:

    • 太棒了!我要花很长时间才能得出这个结论。非常感谢!
    猜你喜欢
    • 2017-04-15
    • 2012-12-30
    • 2021-08-08
    • 2022-01-20
    • 2020-11-05
    • 2020-08-04
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多