PHP 5.4.33 Released

Inserting a Document

Associative arrays are the basic object that can be saved to a collection in the database. A somewhat random "document" might be:

<?php
$doc 
= array(
    
"name" => "MongoDB",
    
"type" => "database",
    
"count" => 1,
    
"info" => (object)array( "x" => 203"y" => 102),
    
"versions" => array("0.9.7""0.9.8""0.9.9")
);
?>

Note that you can have nested arrays and objects. The driver will always store an associative array as an object in the database. A numerically indexed array is stored as an array in case the keys start at 0 and are not interrupted, and as an object if the array keys don't start at 0 or have gaps (ie: 0, 1, 4, 5).

To insert this document, use MongoCollection::insert():

<?php
$connection 
= new MongoClient();
$collection $connection->database->collectionName;

$collection->insert$doc );
?>

See Also

The API documentation on MongoCollection::insert() contains more information about inserting data.

add a note add a note

User Contributed Notes 1 note

up
0
fabian at fabfuel dot de
6 months ago
If you do not specify a custom _id, the driver automatically pushes the generated _id to the given document.
After saving, you can directly access the created _id:

<?php
...
$collection->insert($doc);
var_dump($doc['_id'])

// example output
object(MongoId)#8 (1) {
   
["$id"]=>
   
string(24) "4e2995576803fab768000000"
 
}
To Top