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(...)