我有一个像HostelTbl这样的集合
{
"_id": ObjectId("5ae845b3d2ccda137000595d"),
"Name": "abc",
"Address": "gggswwrerghyjh",
"NoOfFloors": NumberInt(4),
"Approved": "Yes",
"SchoolId": ObjectId("5a8e9025ff24ae113c005d42"),
"RoomsDetails": [
{
"RoomId": "80a1761f-f8ee-a78f-c6ab-6f9bfbdb8ea3",
"FloorNumber": "3",
"RoomNumber": "5",
"RoomType": ObjectId("5ae8267ed2ccda137000595b"),
"NumberOfBeds": "4"
},
{
"RoomId": "56a1761f-f8ee-a78f-c6ab-6f9bfbdb8es3",
"FloorNumber": "3",
"RoomNumber": "4",
"RoomType": ObjectId("5ae8267ed2ccda137000595b"),
"NumberOfBeds": "5"
}
]
}
请注意,它包含嵌入的文档RoomsDetails。现在我只想获取一个 特别是基于RoomId的嵌入式文档
我试过了
public function fetchRoomById()
{
$cursor = $this->collection->aggregate(array(
array(
'$match' => array(
"_id" => new MongoDB\BSON\ObjectID($this->id)),
)
),
array(
'$project' => array(
'RoomsDetails' => array(
'$filter' => array(
'input' => '$RoomsDetails',
'as' => 'Rooms',
'cond' => array(
'$eq' => array('$$Rooms.RoomId', $this->RoomId)
)
)
),
)
)
);
return $cursor->toArray();
}
不返回匹配的嵌入式文档,它返回主文档而不是嵌入文档。
请帮忙
答案 0 :(得分:0)
我已经在我的本地数据库中运行了过滤器查询,它运行正常
db.users.aggregate(
[
{
$project: {
"Name": 1,
"Address": 1,
"NoOfFloors":1,
"Approved": 1,
"SchoolId":1,
items: {
$filter: {
input: "$RoomsDetails",
as: "item",
cond: { $eq: [ "$$item.RoomId", "80a1761f-f8ee-a78f-c6ab-6f9bfbdb8ea3" ] }
}
}
}
},
]);