手册
在线手册:中文  英文

Tutorial

Table of Contents

This is the 10gen-supported PHP driver for MongoDB.

Here's a quick code sample that connects, inserts documents, queries for documents, iterates through query results, and disconnects from MongoDB. There are more details on each step in the tutorial below.

<?php

// connect
$m = new MongoClient();

// select a database
$db $m->comedy;

// select a collection (analogous to a relational database's table)
$collection $db->cartoons;

// add a record
$document = array( "title" => "Calvin and Hobbes""author" => "Bill Watterson" );
$collection->insert($document);

// add another record, with a different "shape"
$document = array( "title" => "XKCD""online" => true );
$collection->insert($document);

// find everything in the collection
$cursor $collection->find();

// iterate through the results
foreach ($cursor as $document) {
    echo 
$document["title"] . "\n";
}

?>

以上例程会输出:

Calvin and Hobbes
XKCD

手册
在线手册:中文  英文

用户评论:

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.

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.

易百教程