sql >> Base de Datos >  >> NoSQL >> MongoDB

MongoDB:cómo insertar un registro usando la funcionalidad de incremento automático

Necesita agregar el campo _id en $ubicación. Y _id debe incluir id. 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:agregue upsert en findAndModify

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 necesita todo el tiempo para volver a crear la conexión

Puede crear MongoDatabase (este patrón singelton)

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

y llame al método de necesidad

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