Mongo Medium Aggregate Request Without Group

I am trying to get the average value of an integer field using the aggregation structure in Mongo. However, I cannot 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, I want to get the average value of the bvc field and any other numeric field for the entire collection in the fastest way (without using MapReduce, since it is less efficient than the aggregation structure).

I tried to group from scratch, but to no avail:

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

I appreciate any help you could provide.

Links: Mongo Aggregation Guide

+9
mongodb aggregation-framework
source share
3 answers

First of all, save the numerical values ​​as numbers. Subsequently, you can use a simple operator to calculate the average value:

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

You can simply use the additional $avg aggregation agents to get average values ​​for your other number fields:

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

So, if your data was really numeric, but it isn’t, and your intention is to exclude documents that have a value greater than zero, then you include $match in the aggregation pipeline to “filter” these documents:

 db.EvaluatedSentiments.aggregate([ { "$match": { "bvc": { "$gt": 0 } }}, { "$group": { "_id": null, "bvc": { "$avg": "$bvc" } }} ]) 
+2
source share
 For more details please visit the following link: https://docs.mongodb.com/manual/reference/operator/aggregation/group/index.html db.EvaluatedSentiments.aggregate([ { $group:{_id:null,avgbvc: {$avg:"$bvc"}} } ]).forEach(printjson) 
-one
source share

All Articles