我有以下MongoDB文档:
{
_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
}
]
}
]
}
我希望能够通过添加所有的
grade_numbers
来更新每辆卡车的average_grade
。但我遇到的问题是,我尝试添加的grade_numbers
在一个数组中,并且这个数组又在另一个数组中。我已尝试使用$unwind
解开卡车和等级数组。以下是我尝试使用的查询:db.col.aggregate([
{$unwind: "$trucks"},
{$unwind: "$trucks.grades"},
{ $project: {
"_id": "$trucks.truck_id",
"trucks.average_grade": { $avg: { $sum: "trucks.grades.grade_number"} }
}
}])
我需要在查询中添加更多内容吗?我想要更新整个文档中的trucks.average_grades
,因为文档中有很多这样的记录。