略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 插入一个文档

2024-05-16

插入一个文档

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

<?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() 方法的文档中有对插入数据的详细说明。

add a note add a note

User Contributed Notes 1 note

up
4
fabian at fabfuel dot de
5 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"
 
}

官方地址:https://www.php.net/manual/en/mongo.tutorial.insert.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3