Home > Back-end >  Average Mongodb with python
Average Mongodb with python

Time:11-11

I've this json file with some 14 arrays each one with a number and I'm trying to get the average of all in MongoDB with python but I'm getting null in the answer.

{'_id': ObjectId('618af03902cd107477e3f2b9'), 
 "Time":[1364,1374,1384],
 "yaw":[0.15,0.3,0.45],
 "pitch":[0.36,0.76,1.08],
 "roll":[-0.13,-0.25,-0.35],
 "ax":[-0.42,-0.41,-0.41],
 "ay":[-0.15,-0.13,-0.1],
 "az":[0.9,0.91,1],
 "gx":[0,0,0],
 "gy":[-0.01,0,-0.01],
 "gz":[0.02,0.02,0.02],
 "mx":[0.26,0.26,0.26],
 "my":[0.01,0.01,0.01],
 "mz":[-0.04,-0.04,-0.07]
 }

I want to average time, yaw, pitch and I have this query in Python for MongoDB:

@app.route('/sta')
def sta():
    docs = db.basetest.aggregate([{"$group": {"_id": '618af03902cd107477e3f2b9', "avgTest" : {"$avg":"Time"}} }])
    for document in docs:
        return document

I'm getting this return:

{
    "_id": "618af03902cd107477e3f2b9",
    "avgTest": null
}

Can anyone help?

CodePudding user response:

You can use $avg operator in a $project stage (or $set or $addFields if you prefer) like this:

db.collection.aggregate([
  {
    "$project": {
      "Time": {"$avg": "$Time"},
      "yaw": {"$avg": "$yaw"},
      "pitch": {"$avg": "$pitch"},
      "roll": {"$avg": "$roll"},
      "ax": {"$avg": "$ax"},
      "ay": {"$avg": "$ay"},
      "az": {"$avg": "$az"},
      "gx": {"$avg": "$gx"},
      "gy": {"$avg": "$gy"},
      "gz": {"$avg": "$gz"},
      "mx": {"$avg": "$mx"},
      "my": {"$avg": "$my"},
      "mz": {"$avg": "$mz"}
    }
  }
])

Example here

  • Related