There are 2 array.
$director = array("name" => "James Cameron");
$cursor = collection("persones")->find( array("name" => "James Cameron") )->limit(1);
if ($cursor->count(true) == 0) {collection("persones")->insert($director);}
$actor = array("name" => "James Cameron", "name" => "Arnold Schwarzenegge");
$cursor = collection("persones")->find( array("name" => "James Cameron") )->limit(1);
if ($cursor->count(true) == 0) {collection("persones")->insert($actor);}
Adding all the directors.
Do check if there are people in the database, if not, then add.
Since the addition of an asynchronous, then the director has not yet been added, and the addition of an actor, added a 2nd time.
James Cameron is added to the base of the 2nd time.
It looks like what you want to do is insert a number of documents, making sure that there is only one entry for each distinct value of the ‘name’ field.
There are two common ways to do this in MongoDB.
The first is to create a unique index on the ‘name’ key and to do your inserts using ‘safe’ mode. If you do the insert that way, PHP will throw an exception when you try to insert a duplicate value.
Reference: http://www.php.net/manual/en/mongocollection.insert.php
Note that if you’re querying on ‘name’, you’ll want to have an index on it anyway for performance reasons. Making it a unique index adds essentially no overhead to this process.
The second way is to do an “upsert”. This is an update command which says “update this document if it exists, and create it if it does not exist yet”. If you do the insert this way, you also won’t get any duplicates.
Reference: http://www.php.net/manual/en/mongocollection.update.php
By the way — there’s nothing that prevents you from using both techniques. You can use the ‘upsert’ for speed, and put in the unique index as an additional check.
As a final note, the code you’re using doesn’t do what I think you think it does.
If you run the following code:
You’ll see the following output: