When using mongo shell I can run something like this:
db.sandbox.insert({"line" : db.eval('storedFunction()') })
or
db.sandbox.insert({"line" : function() {return 1337} })
I was unable to achieve the same effect using php.
What I wish to do is run something similar to
$fnc = "function() {return 123}";
$col = (new Mongo)->database->collection;
$col->insert(['col' => new MongoCode($fnc)]);
and find
{
"_id" : ....,
"col" : 123
}
in the collection. How can I achieve this? Is it even possible?
If you want even more details I’m trying to imitate autoincrement. This function that I’m writing should retrieve the last used value of incremental field, increment it and return the value thus assigning a unique value to the document that is being inserted.
You can’t do what you want with MongoDB, exactly. When you run your example in the shell, it calls the
db.eval...bit first, then passes the computed result as part of the document. The only thing Mongo will evaluate during a write operation are the special modifier fields as part of an update (or upsert, if you want). None of those will let you do a per-collection counter, though.For autoincrement, you’ll need to do two queries. You can use
findAndModifyto atomically increment and retrieve a number, then assign it to yourlinesvalue.Here’s how you’d do it from the shell: