我在mongodb中有三个收藏品,如
employeeTitleTbl contains
{
"_id": ObjectId("5a7c2027d2ccda04d0006070"),
"EmployeeTitleName": "Librarian",
"EmployeeTitleCode": "ji8766",
..
}
DepartmentsTbl contains
{
"_id": ObjectId("5a817402d2ccda13240015a5"),
"DepartmentCode": "149",
"DepartmentName": "Biology",
..
}
EmployeesTbl contains
{
"_id": ObjectId("5a81957bd2ccda13240015a8"),
"EmployeeNumber": "25789998",
"JobTitle": ObjectId("5a7c2008d2ccda04d000606f"),
"Department": ObjectId("5a8173e6d2ccda13240015a4"),
...
}
我对mongodb很新,而且驱动程序也更新了3.6,因此很难在php中找到最新的聚合方法。所以我调整了以下代码,用于添加部门和员工职位的实际值,如" EmployeeTitleName"和" DepartmentName"在EmployeesTbl。
public function fetchAll()
{
$pipeline = array(
array(
'$lookup' => array(
'from' => 'DepartmentsTbl',
'localField' => 'Department',
'foreignField' => '_id',
'as' => 'DepartmentDetails'
)
),
array(
'$lookup' => array(
'from' => 'employeeTitleTbl',
'localField' => 'JobTitle',
'foreignField' => '_id',
'as' => 'JobTitleDetails'
)
),
);
try
{
$cursor = $this->db->EmployeesTbl->aggregate($pipeline);
}
catch(Exception $e){
}
return $cursor->toArray();
}
请用最新方法帮助我!!!
输出就像
array(2){[0] => object(MongoDB \ Model \ BSONDocument)#29(1){[" storage":" ArrayObject":private] => array(25){[" _id"] => object(MongoDB \ BSON \ ObjectId)#10(1){[" oid"] => string(24)" 5a8176c0d2ccda13240015a6" } [" EmployeeNumber"] => string(8)" 25799989" .... ........... [" DepartmentDetails"] => object(MongoDB \ Model \ BSONArray)#27(1){[" storage":" ArrayObject":private] => array(0){}} [" JobTitleDetails"] => object(MongoDB \ Model \ BSONArray)#28(1){[" storage":" ArrayObject":private] => array(0){}}}} [1] = .........
答案 0 :(得分:0)
您需要使用$ lookup来连接两个或更多表格,例如..
db.employeeTitle.aggregate([{
$lookup: {
from: 'employees',
localField: 'EmployeeTitleName',
foreignField: '_id',
as: 'employeeData'
}
},
{ $unwind: '$employeeData' },
{
$project: { profile: '$employeeData' }
}
])
它连接两个表employeeTitle和员工,并为您提供有关员工的完整信息。