MongoDB
 sql >> Cơ Sở Dữ Liệu >  >> NoSQL >> MongoDB

MongoDB - cách chèn bản ghi bằng chức năng autoincrement

Bạn cần thêm trường _id vào $ location. Và _id bạn phải có id. Ví dụ:

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

Đề xuất của tôi:thêm nâng cấp trong findAndModify

Nó sẽ hiệu quả với bạn:

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

Trong một dự án thực, bạn không cần tất cả thời gian để tạo lại kết nối

Bạn có thể tạo MongoDatabase (mẫu này singelton)

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

và gọi phương thức cần

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


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Đồ thị DBs so với DB tài liệu so với Triplestores

  2. MongoDB:Kéo nhiều tài liệu ngẫu nhiên từ một bộ sưu tập

  3. Tự động cập nhật nhiều tài liệu VÀ gửi lại chúng

  4. Looping Array và kiểm tra bộ sưu tập MongoDB trong vòng lặp (Async)

  5. Giao dịch MongoDB