Mongo average aggregation query with no group

前端 未结 3 1586
生来不讨喜
生来不讨喜 2020-12-03 21:39

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. <

相关标签:
3条回答
  • 2020-12-03 22:17
    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)
    
    0 讨论(0)
  • 2020-12-03 22:32

    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" } 
      } 
    })
    
    0 讨论(0)
  • 2020-12-03 22:38

    So if your data actually was numeric which is it not and your intention is to exclude the documents that have a "greater than zero" value then you include a $match statement in your aggregation pipeline in order to "filter" out these documents:

    db.EvaluatedSentiments.aggregate([
        { "$match": {
            "bvc": { "$gt": 0 }
        }},
        { "$group": {
            "_id": null,
            "bvc": { "$avg": "$bvc" }
        }}
    ])
    
    0 讨论(0)
提交回复
热议问题