mongo-php-tutorial-php-insert-6

  • Tutorial
  • Inserting a Document

  • Inserting a Document
  • Inserting a Document

    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.