我有一个旅馆表
{
_id: ...,
Name: ....,
SchoolId: ...,
AllotmentsDetails: [
...,
...,
],
RoomsDetails:
[
{
NumberOfBeds: 4
....
},
{
NumberOfBeds: 5
....
}
]
}
我想计算一家旅馆的总容量。在上面的示例中,它应该为9(RoomDetails嵌入式文档中的所有NumberOfBeds字段之和)。我已经尝试过下面的代码行。
$query = array('SchoolId' => new MongoDB\BSON\ObjectID($this->SchoolId));
// Actual Aggregation
$pipeline = array(
array(
'$match' => $query
),
[ '$addFields'=> [
'AllotmentsDetails'=> [
'$cond'=> [
'if'=> [
'$ne'=> [ [ '$type'=> '$AllotmentsDetails' ], 'array' ]
],
'then'=> [],
'else'=> '$AllotmentsDetails'
]
]
]],
[
'$addFields' => [
'NonExpiredAllotments' => [
'$map' => [
'input' => '$AllotmentsDetails',
'as' => 'item',
'in' => [
'$cond' => [
['$gt' => ['$$item.ToDate', new MongoDB\BSON\UTCDateTime((new DateTime())->getTimestamp() * 1000)]],
'$$item.AllotmentId',
false
]
]
]
]
]
],
[
'$addFields' => [
'TotalNumberOfCapacities' => [
['$sum' => [ 'RoomsDetails.NumberOfBeds']]
]
]
]
);
$cursor = $this->collection->aggregate($pipeline)
输出
array(1) { [0]=> object(MongoDB\Model\BSONDocument)#37 (1) { ["storage":"ArrayObject":private]=> array(12) { ["_id"]=> object(MongoDB\BSON\ObjectId)#13 (1) { ["oid"]=> string(24) "5bc087ddd2ccda0eb4004711" } ["Name"]=> string(3) "rrr" ..............
} ["TotalNumberOfCapacities"]=> object(MongoDB\Model\BSONArray)#36 (1) { ["storage":"ArrayObject":private]=> array(1) { [0]=> int(0) } } } } }
计算不正确,请帮助!
这是实际的嵌入式文档
"RoomsDetails": [
{
"RoomId": "9f9b510c-9753-f410-8f79-f0b04affb7a2",
"FloorNumber": "1",
"RoomNumber": "101",
"RoomType": ObjectId("5b0ceee0bb2c561448001cc5"),
"NumberOfBeds": "4",
"Available": NumberInt(3),
"BayId": ObjectId("5bc087dcd2ccda0eb400470f")
},
{
"RoomId": "789b510c-9753-f410-8f79-f0b04affb768",
"FloorNumber": "1",
"RoomNumber": "102",
"RoomType": ObjectId("5b0ceee0bb2c561448001cc5"),
"NumberOfBeds": "5",
"Available": NumberInt(3),
"BayId": ObjectId("5bc087dcd2ccda0eb400470f")
}
],