我有以下mongo查询。在这个例子中,我得到一个子文档(带有查找)" transport_type"。此子文档具有许多属性。我只想要id和名字。如何将$ project与$ arrayElemAt和$ filter结合起来?现在它返回所有字段
$stations = Station::raw(function ($collection) use ($match){
return $collection->aggregate([
[
'$lookup' => [
'as' => 'transport_type',
'from' => 'transport_types',
'foreignField' => '_id',
'localField' => 'transport_type_id'
]
],
[
'$match' => $match
],
[
'$project' => [
'name' => 1,
'code' => 1,
'area_id' => 1,
'transport_type' => [
'$arrayElemAt' => [
[
'$filter' => [
'input' => '$transport_type',
'as' => 'transport_type_',
'cond' => [ '$eq' => [ '$$transport_type_.deleted_at', null ] ],
]
], 0
]
],
'active' => 1
]
],
[
'$sort' => [
'name' => 1
]
]
]);
});
答案 0 :(得分:1)
$stations = Station::raw(function ($collection) use ($match){
return $collection->aggregate([
[
'$lookup' => [
'as' => 'transport_type',
'from' => 'transport_types',
'foreignField' => '_id',
'localField' => 'transport_type_id'
]
],
[
'$match' => $match
],
[
'$project' => [
'name' => 1,
'code' => 1,
'area_id' => 1,
'transport_type' => [
'$let' => [
'vars' => [
'field' => [
'$arrayElemAt' => [
[
'$filter' => [
'input' => '$transport_type',
'as' => 'transport_type_',
'cond' => [ '$eq' => [ '$$transport_type_.deleted_at', null ] ]
]
], 0
]
]
],
'in' => [
['id' => '$$field._id','name' => '$$field.name']
]
]
],
'active' => 1
]
],
[
'$sort' => [
'name' => 1
]
]
]);
});