没有组的Mongo平均聚合查询 [英] Mongo average aggregation query with no group

查看:69
本文介绍了没有组的Mongo平均聚合查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Mongo中的聚合框架来获取整个字段的平均值.但是我似乎找不到任何没有组参数的使用它的例子.

我具有以下文档结构:

  {
      "_id" : ObjectId("5352703b61d2739b2ea44e4d"),
      "Semana" : "2014-02-23 - 2014-03-01",
      "bolsaDeValores" : "7",
      "bvc" : "8",
      "dollar" : "76",
      "ecopetrol" : "51",
      "dollarPrice" : "18"
 }
 

我基本上想做的是以最快的方式获取整个集合的bvc字段和其他任何数值的平均值(不使用MapReduce,因为它的效率不如Aggregation Framework). /p>

我也尝试在大于零的基础上进行分组,但无济于事:

 db.EvaluatedSentiments.aggregate([
    { "$group": { 
        "bvc" : {"$gt:0"}
        }, 
        {
            "bvc" : { "$avg" : "$bvc"}
        }
    }
])
 

感谢您能提供的任何帮助.

参考文献: Mongo聚合手册

解决方案

首先将数值存储为数字.然后,您可以使用简单的语句来计算平均值:

db.collection.aggregate({ 
  "$group": {
    "_id": null, 
    "avg_bvc": { "$avg": "$bvc" } 
  } 
})

您可以简单地使用更多的$avg聚合运算符来获取其他数字字段的平均值:

db.collection.aggregate({ 
  "$group": {
    "_id": null, 
    "avg_bvc": { "$avg": "$bvc" }, 
    "avg_dollar": { "$avg": "$dollar" } 
  } 
})

I am trying to get the average of a whole field using the aggregation framework in Mongo. However i can't seem to find any example that uses it without a group parameter.

I have the following document structure:

 {
      "_id" : ObjectId("5352703b61d2739b2ea44e4d"),
      "Semana" : "2014-02-23 - 2014-03-01",
      "bolsaDeValores" : "7",
      "bvc" : "8",
      "dollar" : "76",
      "ecopetrol" : "51",
      "dollarPrice" : "18"
 }

Basically what i want to do is get the average value of the bvc field, and any other numeric one, for the whole collection in the fastest possible way (without using MapReduce as it is less efficient than the Aggregation Framework).

I have tried to group on a greater than zero basis as well but to no avail:

db.EvaluatedSentiments.aggregate([
    { "$group": { 
        "bvc" : {"$gt:0"}
        }, 
        {
            "bvc" : { "$avg" : "$bvc"}
        }
    }
])

I appreciate any help you could provide.

References: Mongo aggregation manual

解决方案

First of all store numerical values as numbers. Afterwards you can use a simple statement to calculate the average:

db.collection.aggregate({ 
  "$group": {
    "_id": null, 
    "avg_bvc": { "$avg": "$bvc" } 
  } 
})

You can simply use more $avg aggregation operators to get averages for your other numeric fields:

db.collection.aggregate({ 
  "$group": {
    "_id": null, 
    "avg_bvc": { "$avg": "$bvc" }, 
    "avg_dollar": { "$avg": "$dollar" } 
  } 
})

这篇关于没有组的Mongo平均聚合查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆