Mongo average aggregation query with no group

前端 未结 3 1589
生来不讨喜
生来不讨喜 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条回答
  •  猫巷女王i
    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" } 
      } 
    })
    

提交回复
热议问题