SQL >> Base de Datos >  >> NoSQL >> MongoDB

MongoDB: cómo insertar un registro con funcionalidad de autoincremento

Necesitas añadir el campo _id en $location. Y _id debe ser el id que incrementas. Ejemplo:

function add_playbook_history_record($location) { $m = new MongoClient("mongodb://10.1.1.111:27017"); $db = $m->testdb; $collection = $db->testcollection; $location['_id'] = getNextSequence('playhistid') $cursor = $collection->insert($location); } 

Mi recomendación: añade upsert en findAndModify

Esto te funcionará:

 function getNextSequence($name) { $m = new MongoClient("mongodb://10.1.1.111:27017"); // In a real project, you do not need all the time to re-create the connection $db = $m->testdb; $collection = $db->counters; $result = $collection->findAndModify( ['_id' => $name], ['$inc' => ['seq' => 1]], ['seq' => true], ['new' => true, 'upsert' => true] ); if (isset($result['seq'])) { return $result['seq']; } else { return false; } } 

En un proyecto real, no necesitas recrear la conexión todo el tiempo

Puedes crear la clase MongoDatabase (patrón singleton)

class MongoDatabase{ private function __construct(){} public static function getInstance(){...} // return MongoClient } 

y llamar al método que necesites

MongoDatabase::getInstance()->selectCollection('counters')->findAndModify(...)