我有一个像这样的数据集合
"Name": "....",
...
"RoomStatusDetails": [
{
"StatusEntryId": ObjectId("5be1895dbb2c5620c4003ae0"),
"RoomId": "41964158-0131-7b55-7781-a29084879e1a",
"CurrentStatus": ObjectId("5bd17295d2ccda11f0007765"),
"StartDate": ISODate("2018-11-06T05:00:00.0Z"),
"Notes": "",
"Discrepancy": "",
"Waiver": "",
"TFlight": "",
"IsActive": "Inactive"
},
{
"StatusEntryId": ObjectId("5be1896cbb2c5620c4003ae1"),
"RoomId": "41964158-0131-7b55-7781-a29084879e1a",
"CurrentStatus": ObjectId("5bd17295d2ccda11f0007766"),
"StartDate": ISODate("2018-11-06T05:00:00.0Z"),
"Notes": "",
"Discrepancy": "",
"Waiver": "",
"TFlight": "",
"IsActive": "Active"
},
{
"StatusEntryId": ObjectId("5bf4e8a83250041388000edf"),
"RoomId": "d72136ac-b295-d4ea-2d32-0f9ef26b7df1",
"CurrentStatus": ObjectId("5bd17295d2ccda11f0007766"),
"StartDate": ISODate("2018-11-26T23:00:00.0Z"),
"Notes": "",
"Discrepancy": "",
"Waiver": "",
"TFlight": "",
"IsActive": "Active"
},
{
"StatusEntryId": ObjectId("5bf4e8db3250041388000ee0"),
"RoomId": "4c980185-65eb-eece-8176-7f187eed3132",
"CurrentStatus": ObjectId("5bd17295d2ccda11f0007765"),
"StartDate": ISODate("2018-11-18T23:00:00.0Z"),
"Notes": "",
"Discrepancy": "",
"Waiver": "",
"TFlight": "",
"IsActive": "Active"
},
{
"StatusEntryId": ObjectId("5bf4e97f3250041388000ee1"),
"RoomId": "407225eb-2990-263b-4112-068d3ef0e1b2",
"CurrentStatus": ObjectId("5bd17295d2ccda11f0007768"),
"StartDate": ISODate("2018-12-05T23:00:00.0Z"),
"Notes": "",
"Discrepancy": "",
"Waiver": "",
"TFlight": "",
"IsActive": "Active"
}
],
我正在尝试以下代码行
$this->collection->aggregate(array(
array(
'$project' => array(
'RoomStatusDetails' => array(
'$filter' => array(
'input' => '$RoomStatusDetails',
'as' => 'item',
'cond' => array(
'$or' => [
['$eq' => ['$$item.CurrentStatus', new MongoDB\BSON\ObjectID($this->CAOutOfService)]],
['$eq' => ['$$item.CurrentStatus', new MongoDB\BSON\ObjectID($this->OutOfService)]]
],
['$eq' => ['$$item.IsActive', 'Active']]
)
)
),
'Name' => 1,
'Address' => 1,
'NoOfFloors' => 1,
'Image' => 1,
'Bay' => 1,
'Approved' => 1,
'RoomsDetails' => 1,
'AllotmentsDetails' => 1,
//'TotalNumberOfCapacitiesArray' => 1
)
),
))->toArray();
我正在尝试投影嵌入式文档RoomStatusDetails,并且仅尝试获取其中$ this-> CAOutOfService或$ this-> OutOfService变量分别存在的“当前状态”可以为“ 5bd17295d2ccda11f0007765”或“ 5bd17295d2ccda11f0007766”的那些RoomStatusDetails数据。而他们的IsActive为“有效”。
上面的代码抛出错误“表示表达式的对象必须具有一个完全相同的字段:{$ or:[{$ eq:[\“ $$ item.CurrentStatus \”,ObjectId('5bd17295d2ccda11f0007769')]}, {$ eq:[\“ $$ item.CurrentStatus \”,ObjectId('5bd17295d2ccda11f0007766')]}],0:{$ eq:[\“ $$ item.IsActive \”,\“ Active \”]}} “
请帮助!!!
答案 0 :(得分:1)
您可以这样构建查询
db.col.aggregate([{
"$project": {
"RoomStatusDetails": {
"$filter": {
"input": "$RoomStatusDetails",
"as": "stat",
cond: {
"$and": [{
$or: [{
$eq: ["$$stat.CurrentStatus", ObjectId("5bd17295d2ccda11f0007766")]
},
{
$eq: ["$$stat.CurrentStatus", ObjectId("5bd17295d2ccda11f0007765")]
}
]
},
{
$eq: ["$$stat.IsActive", "Active"]
}
]
}
}
}
}
}
])