I'm trying to insert data from PHP to Mongo. I am using the new MongoDB extension for PHP.
When inserting data, the _id needs to be autoincremented therefore I created this server-side Javascript to run with Mongo:
function getNextSequence(name){
var ret = db.counters.findAndModify(
{
query:{_id:name},
update:{$inc:{seq:1}},
new:true
}
);
this works using the following collection:
db.counters.insert({_id:1,seq:0})
I am trying to run this function from PHP therefore I'm using the MongoDB\BSON\Javascript class in order to run Javascript as follows:
//the script in string format
$script = 'function getNextSequence(name){var ret = db.counters.findAndModify({query:{_id:name},update:{$inc:{seq:1}},new:true});return ret.seq;}';
$bulk->insert(['_id' => (new MongoDB\BSON\Javascript($script),'name' => "test", 'lastname' => "test"]);
It inserts in the collection however the _id field is of Function type and contains the function, not the returned value of the function.
How do I get the returned value of the function instead? My question is about the PHP code needed in order to accomplish it, not about the difference between back-end and front-end.