文字

插入一个文档

关联数组是能插入集合的最基本结构。 一般的“文档”结构可能是这样:

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

注意:你可以嵌套数组、对象。驱动会把关联数组保存为 js对象,从0开始的连续数字下标数组保存为 js数组,不从0开始或有间断的(如0,1,4,5)数组保存为 js对象。 译注:即:只有从0开始的连续数字下标数组保存为数组,其他复杂类型均为对象。

要插入这个文档,使用 MongoCollection::insert() 方法:

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

$collection -> insert $doc  );
?>

参见

MongoCollection::insert() 方法的文档中有对插入数据的详细说明。

用户评论:

[#1] fabian at fabfuel dot de [2014-03-01 06:21:39]

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"
  }

上一篇: 下一篇: