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.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Manual
- Making a Connection
- Getting a Database
- Getting A Collection
- Inserting a Document
- Finding Documents using MongoCollection::findOne
- Adding Multiple Documents
- Counting Documents in A Collection
- Using a Cursor to Get All of the Documents
- Setting Criteria for a Query
- Getting A Set of Documents With a Query
- Creating An Index
Коментарии
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"
}