本文共 2460 字,大约阅读时间需要 8 分钟。
连接MongoDB数据库时,可以使用以下方式:
$conn = new Mongo();// 连接本地主机,默认端口$conn = new Mongo("172.21.15.69");// 连接远程主机$conn = new Mongo("xiaocai.loc:10086");// 连接指定端口的远程主机$conn = new Mongo("xiaocai.loc", array("replicaSet" => true));// 持久连接$conn = new Mongo("mongodb://sa:123@localhost");// 连接多个服务器$conn = new Mongo("mongodb://localhost:27017,localhost:27018");// 使用域套接字$conn = new Mongo("mongodb://admin_miss:miss@localhost:27017/test"); 详细信息可参考 PHP手册 - 连接MongoDB。
选择数据库和集合时,可以使用以下方式:
$db = $conn->mydb;// 或者$db = $conn->selectDB("mydb");$collection = $db->column;// 或者$collection = $conn->mydb->column; 注意:数据库和集合在不存在时会自动创建。
向集合中插入数据:
$array = array("column_name" => "col" . rand(100, 999), "column_exp" => "xiaocai");$result = $collection->insert($array); 插入成功返回 true。
安全插入数据:
$result = $collection->insert($array, true);
返回数组,包含 err、n 和 ok。
完整格式:
insert(array $a, array $options = array())
参数包括 safe、fsync 和 timeout,默认值均为 false。
更新文档时,可以使用以下方式:
$where = array("column_name" => "col123");$newdata = array("column_exp" => "GGGGGGG", "column_fid" => 444);$result = $collection->update($where, array("$set" => $newdata)); 替换更新:
$newdata = array("column_exp" => "HHHHHHHHH", "column_fid" => 123);$result = $collection->update($where, $newdata); 批量更新:
$newdata = array("column_exp" => "multiple", "91u" => 684435);$result = $collection->update($where, array("$set" => $newdata), array("multiple" => true)); 删除节点:
$result = $collection->update($where, array("$unset" => "column_exp")); 删除文档时,可以使用以下方式:
$collection->remove(array("column_name" => "col399"));$collection->remove(); 删除指定 ObjectId:
$id = new MongoId("4d638ea1d549a02801000011");$collection->remove(array("_id" => (object)$id)); 查询文档时,可以使用以下方式:
echo "count: " . $collection->count();
带条件查询:
echo "count: " . $collection->count(array("type" => array("$gt" => 50, "$lte" => 74))); 查询多条记录:
$cursor = $collection->find();foreach ($cursor as $id => $value) { echo "$id: " . var_dump($value) . "\n";} 查询一条记录:
$cursor = $collection->findOne();
限制查询结果:
$cursor = $collection->find()->limit(5)->skip(0);
排序查询结果:
$cursor = $collection->find()->sort(array("age" => -1, "type" => 1)); 创建索引:
$collection->ensureIndex(array("age" => 1, "type" => -1));$collection->ensureIndex(array("age" => 1, "type" => -1), array("background" => true));$collection->ensureIndex(array("age" => 1, "type" => -1), array("unique" => true)); MongoDB 不支持文档聚类功能,以上内容仅为操作指南。
转载地址:http://qevfk.baihongyu.com/