Du skal tilføje _id felt i $location.Og _id skal du inkludere id.Eksempel:
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);
}
Min anbefaling:Tilføj upsert i findAndModify
Det vil fungere for dig:
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;
}
}
I et rigtigt projekt behøver du ikke hele tiden at genoprette forbindelsen
Du kan oprette MongoDatabasen (dette mønster singelton)
class MongoDatabase{
private function __construct(){}
public static function getInstance(){...} // return MongoClient
}
og kalde behov metode
MongoDatabase::getInstance()->selectCollection('counters')->findAndModify(...)