PHP Velho Oeste 2024

ドキュメントの追加

連想配列は、データベース内のコレクションに保存できる基本的なオブジェクトです。 何らかの "ドキュメント" はこのような形式になります。

<?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")
);
?>

配列やオブジェクトをネストできることに注目しましょう。 ドライバは、連想配列を常にオブジェクトとしてデータベースに格納します。 数値添字の配列は、もし配列のキーは 0 から始まる連番の場合は配列として格納します。 0 から始まらない場合や途中に添字の抜けがある場合 (0, 1, 4, 5 など) は、オブジェクトとして格納します。

ドキュメントを追加するには MongoCollection::insert() を使います。

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

$collection->insert$doc );
?>

参考

MongoCollection::insert() の API ドキュメントに、 データの追加に関する詳細な情報があります。

add a note add a note

User Contributed Notes 1 note

up
4
fabian at fabfuel dot de
10 years 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