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
2
Answers
Thank you my friend, the problem was in the double quotes.
doing this fixed it
First I would suggest to optimize your pipeline:
{ $match: {_id: {$ne: null}}}
does not make any sense, because_id
always exists and is never null. Skip this stage.Instead of
you can use
or even shorter just:
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"
.