我在mongodb中有一个表TblStudent,如
{
"_id": ObjectId("5baa85041d7859f40d000029"),
"Name": "John Doe",
"RollNo": 12,
"Class": "Ist"
....
}
我还有另一个表TblRoute之类的
{
"_id": ObjectId("5baa818d1d78594010000029"),
"Name": "New york City",
"StopDetails": [
{
"StopId": "abc777",
"Name": "Block no 3"
},
{
"StopId": "abc888",
"Name": "Block no 4"
}
],
"NumberOfSeats": "10",
"StudentDetails": [
{
"StudentId": ObjectId("5baa85041d7859f40d000029"),
"VehicleId": "7756"
},
{
"StudentId": ObjectId("5baa85f61d7859401000002a"),
"VehicleId": "7676"
}
]
}
我正在使用mongodb 3.6平台。获得在线帮助后,我正在使用以下代码行!!!
$query = ['_id' => new MongoDB\BSON\ObjectID($this->id)];
$cursor = $this->db->TblRoute->aggregate([
['$match' => $query],
['$lookup' => [
'from' => "TblStudent",
'let' => ['studentid' => '$StudentDetails.StudentId'],
'pipeline' => [
['$match' => ['$expr'=> ['$in' => ['$_id','$$studentid' ]]]],
['$project' => ['Name'=> 1,'RollNo' => 1, '_id'=> 1]]
],
'as' => 'studentObjects',
]],
['$unwind'=> '$studentObjects' ],
// Group back to arrays
[ '$group'=> [
'StudentDetails.StudentId'=> '$_id',
'StudentDetails.StudentData'=> [ '$push'=> '$studentObjects' ]
]]
]);
它抛出错误消息,消息为“ StudentDetails.StudentId”字段必须是累加器对象”,未捕获的异常“ MongoDB \ Driver \ Exception \ RuntimeException”
基本上,我想使用查找聚合从另一个表中获取数据。因此,在获得在线帮助和进一步研究之后,我能够编写以上代码。这里的主要问题是$ unwind语句之前的代码将输出生成为单独的数组。如果我们在$ lookup中写'as'=>'StudentDetails.studentObjects',则数据将被新数据覆盖,从而导致其他字段(如Vehicleid等)丢失。 保存它们。因此,在研究之后,我尝试添加$ group将其放回StudentDetails嵌入式文档中。
所需的输出
{
"_id": ObjectId("5baa818d1d78594010000029"),
"Name": "New york City",
"StopDetails": [
.....
],
"StudentDetails": [
{
"StudentId": ObjectId("5baa85041d7859f40d000029"),
"VehicleId": "7756",
"StudentData": [
"Name": ..
"RollNo":...
]
},
{
"StudentId": ObjectId("5baa85f61d7859401000002a"),
"VehicleId": "7676",
"StudentData": [
"Name": ..
"RollNo":...
]
}
]
}
请帮助我解决问题
答案 0 :(得分:1)
您可以执行以下操作
myop