3

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.

Felipe Sulser
  • 1,185
  • 8
  • 19
  • Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Epodax Apr 21 '16 at 10:43
  • @Epodax my question is not about the fundamentals about server side vs client side but it's more a question of which function or method I can call to execute from PHP – Felipe Sulser Apr 21 '16 at 10:47
  • Actually we get about one of these every couple of weeks. You are following the code **example** from ["Create an Auto-Incrementing Sequence Field"](https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/) and just like every question like this before, you failed to understand that the idea is to **implement in your own language** and not run as JavaScript code in the server. The common mistake is no doubt because all of your brains think in terms of **stored procedures**. There are no stored procedures in MongoDB. Implement in your chosen language instead. – Neil Lunn Apr 21 '16 at 11:03
  • I am not storing any procedure in back end, I'm creating the Javascript function in a string and then passing it to the constructor of the BSON\Javascript class. My question is how to execute that Javascript class instead of storing it as a Function in the collection. Because in the documentation, there's no reference to that http://php.net/manual/en/class.mongodb-bson-javascript.php – Felipe Sulser Apr 21 '16 at 11:05

0 Answers0