MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

MongoDB - come inserire record utilizzando la funzionalità di incremento automatico

Devi aggiungere il campo _id in $location.E _id devi inc id.Esempio:

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);
}

Il mio consiglio:aggiungi upsert in findAndModify

Lavorerà per te:

    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;
        }
    }

In un progetto reale, non è necessario tutto il tempo per ricreare la connessione

Puoi creare il MongoDatabase (questo modello singelton)

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

e chiama il metodo di necessità

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