Skip to content

Instantly share code, notes, and snippets.

@gerasimua
Created October 15, 2014 14:19
Show Gist options
  • Save gerasimua/d5b568e340349a7f5208 to your computer and use it in GitHub Desktop.
Save gerasimua/d5b568e340349a7f5208 to your computer and use it in GitHub Desktop.
Mongo autoincrement field
<?php
$func = new MongoCode(
'function insertDocument(doc, targetCollection) {
targetCollection = db[targetCollection];
var cursor = targetCollection.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1);
var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1;
doc._id = NumberInt(seq);
var results = targetCollection.insert(doc);
return doc._id;
}'
);
$response = $db->execute($func, array($data, $collectionName));
echo $response['retval']['value']; //insert id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment