书写技术成长之路

PHP MongoDB 基本使用

PHP56需要安装php56-mongo, 而不是php56-mongodb

安装 brew install php56-mongo

然后重启PHP-FPM brew services restart php56

连接MongoDB和基本使用

<?php

$mongodb = new MongoClient;

// select a database
$db = $mongodb->test;

// select a collection
$collection = $db->test;

// 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 title not null in the collection
$cursor = $collection->find(['title' => ['$ne' => null]]);

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

MongoDB 插入

<?php

/**
 * MongoDB Insert Operation
 */
$mongoDB = new MongoClient;

// select collection
$collection = $mongoDB->example->users;

$insertOneResult = $collection->insert([
    'username' => 'admin',
    'email' => 'admin@example.com',
    'name' => 'Admin User',
    'creat_time' => time(),
]);

var_dump($insertOneResult);

MongoDB 查询

<?php

/**
 * MongoDB Query 
 */

$mongoDB = new MongoClient();

$collection = $mongoDB->example->users;

$document = $collection->findOne(['username' => 'admin']);

var_dump($document);

$cursor = $collection->find(['username' => 'admin'], ['username' => true, 'email' => true, 'create_time' => true])->sort(['create_time' => -1])->limit(2);

foreach ($cursor as $document) {
    var_dump($document);
}

参考

php.net #The MongoCollection class#