Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

mongodb - Mongo average aggregation query with no group

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" } 
  } 
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...