my node codes work, but when I want to write it in PHP, it does not work. can you help?
node code mongo sh works without any problems
db.mevcutlot.aggregate([{$match: {_id: {$ne: null}}},
{ $sort: { ederi: -1 } },
{ $group: { _id: '$firmasaf', data: { $push: '$$ROOT' } } },
{ $project: { _id: 0, data: { $arrayElemAt: ["$data", 0] } } },
{ $replaceRoot: { newRoot: "$data" } }])
php code
$pipeline=array(
array(
'$match' => array(
'_id' => ['$ne'=>NULL],
)
),
array(
'$sort' => array(
'ederi'=> -1,
)
),
array(
'$group' => array(
'_id' => '$firmasaf', 'data'=> ['$push'=> '$$ROOT'],
)
),
array(
'$project' => array(
'_id' => 0,
'data' => ['$arrayElemAt'=> ["$data", 0]],
)
),
array(
'$replaceRoot' => array(
'newRoot'=> "$data",
)
),
);
$mana = $mevcutlot->aggregate($pipeline)->toArray();
print_r($mana);
I could not return any results
First I would suggest to optimize your pipeline:
db.mevcutlot.aggregate([
{ $match: {_id: {$ne: null}}},
{ $sort: { ederi: -1 } },
{ $group: { _id: '$firmasaf', data: { $push: '$$ROOT' } } },
{ $project: { _id: 0, data: { $arrayElemAt: ["$data", 0] } } },
{ $replaceRoot: { newRoot: "$data" } }
])
{ $match: {_id: {$ne: null}}}
does not make any sense, because _id
always exists and is never null. Skip this stage.
Instead of
{ $sort: { ederi: -1 } },
{ $group: { _id: '$firmasaf', data: { $push: '$$ROOT' } } },
{ $project: { _id: 0, data: { $arrayElemAt: ["$data", 0] } } },
you can use
{ $sort: { ederi: -1 } },
{ $group: { _id: '$firmasaf', data: { $first: '$$ROOT' } } },
or even shorter just:
{ $group: { _id: '$firmasaf', data: { $top: { output: '$$ROOT', sortBy: { ederi: -1 } } } } },
It should perform better than your query.
Now, regarding your problem: When you use double-quoted string, then variables are replaced by values, see String interpolation
Because $data
variable is most likely empty, '$arrayElemAt'=> ["$data", 0]
is substituted to '$arrayElemAt'=> ["", 0]
and 'newRoot'=> "$data"
becomes 'newRoot'=> ""
. You should get a warning "Warning: Undefined variable $data in..."
Use single-quotes everywhere or escape the $
, e.g. "\$data"
.