I have the following MongoDB document:
{
_id: ObjectId(),
company_name: "Name",
registered: 2/21/2015 2:00,
trucks: [
{
truck_id: "TEB7622",
weight: 88.33,
capacity: 273.333,
length: 378.333,
width: 377.383,
average_grade: 2.5,
grades: [
{
grade_number: 4,
timestamp: 2/21/2015 2:00
}
]
},
{
truck_id: "TEB5572",
weight: 854.33,
capacity: 2735.333,
length: 378.333,
width: 37.383,
average_grade: 3.8,
grades: [
{
grade_number: 4,
timestamp: 2/21/2015 2:00
}
]
}
]
}
I want to update each truck's average_grade by adding all the grade_numbers. The problem I'm having is that the grade_numbers I am trying to add are in an array within an array. I have tried using $unwind to unwind both trucks and grades arrays.
This is the query I have tried using:
db.col.aggregate([
{$unwind: "$trucks"},
{$unwind: "$trucks.grades"},
{ $project: {
"_id": "$trucks.truck_id",
"trucks.average_grade": { $avg: { $sum: "trucks.grades.grade_number"} }
}
}])
Do I have to add something more to my query? I want to update ALL of the trucks.average_grades, since there a lot of them in the document I am trying to update.
company_idfield? Or each grade its own document? You do not want to rely on a double unwind aggregation pipeline for a normal query, so I would not recommend the below solution unless the query is uncommon.