文字

教程

Table of Contents

  • 连接数据库
  • 获取数据库实例
  • 获取集合实例
  • 插入一个文档
  • 使用 MongoCollection::findOne 方法
  • 添加多个文档
  • 计算文档数量
  • 使用游标获取所有文档
  • 设置查询条件
  • 获取一个子集
  • 建立索引

这个驱动是由 10gen 公司官方支持的 MongoDB 驱动

这是一个示例程序,它包含 连接数据库、插入文档、查询文档、遍历查询结果、断开链接。 实例中的每一步都有更详细的说明(注释)。

<?php

// 链接服务器
$m  = new  MongoClient ();

// 选择一个数据库
$db  $m -> comedy ;

// 选择一个集合( Mongo 的“集合”相当于关系型数据库的“表”)
$collection  $db -> cartoons ;

// 插入一个文档(译注:“文档”相当于关系型数据库的“行”)
$document  = array(  "title"  =>  "Calvin and Hobbes" "author"  =>  "Bill Watterson"  );
$collection -> insert ( $document );

// 添加另一个文档,它的结构与之前的不同
$document  = array(  "title"  =>  "XKCD" "online"  =>  true  );
$collection -> insert ( $document );

// 查询集合中的所有文档
$cursor  $collection -> find ();

// 遍历查询结果
foreach ( $cursor  as  $document ) {
    echo 
$document [ "title" ] .  "\n" ;
}

?>

以上例程会输出:

Calvin and Hobbes
XKCD

用户评论:

[#1] pgl at yoyo dot org [2013-09-17 13:44:48]

To use a collection with periods in its name, quote it with braces:

<?php
$m 
= new MongoClient();

$cursor $m->test->{'test.test'}->find();

## equivalent to the following:
#$db = $m->test;
#$collection = $db->{'test.test'};
#$cursor = $collection->find();

foreach ($cursor as $doc) {
    
print_r($doc);
?>

[#2] Josh Heidenreich [2010-12-08 22:28:19]

If you are getting "writing more" shown at random places on the screen, it's a MongoDB connector bug in 1.0.5.

Bug report: http://jira.mongodb.org/browse/PHP-91

Update to the latest connector driver and it should go away.

[#3] php at whoah dot net [2010-04-24 22:57:19]

Make sure array keys consecutive before inserting. As of 1.0.6 driver, the following will end up as an object of key:value pairs, instead of an array, because it's trying to maintain the 0 and 2 keys:

$array = array('a', 'b', 'c');
unset($array[1]);

$document = array(
'embedded' => $array,
);

// assuming local
$mongo = new Mongo();
$mongo->test->test->insert($document);

mongodb result:
{ "_id" : ObjectId(...), "embedded" : { "0" : "a", "2" : "c" } } 

This is bad if you plan on indexing the embedded property as an array because objects and arrays are indexed differently.

Whether the behaviour will change or not, this is logged here: http://jira.mongodb.org/browse/PHP-104

If you know about it, it's not major, just use a sort() before inserting, or use array_* methods to remove elements instead of unset() -- anything that will re-adjust keys.

上一篇: 下一篇: