跳到主要内容

三十四、MongoDB PHP

MongoDB PHP 在各平台上的安装及驱动包下载请查看: PHP 安装 MongoDB 扩展驱动

如果你使用的是 PHP7,请移步: PHP7 MongoDB 安装与使用

PHP 连接 MongoDB 和 选择一个数据库

为了确保正确连接,我们需要指定数据库名,如果数据库在 mongoDB 中不存在, mongoDB 会自动创建

<?php
/*
* filename: main.php
* author: pottercoding.cn 程序员波特,程序员编程资料站(pottercoding.cn)
* Copyright © 2015-2065 pottercoding.cn. All rights reserved.
*/
$m = new MongoClient(); // 连接默认主机和端口为:mongodb://localhost:27017
$db = $m->souyunku; // 切换到 "souyunku" 数据库

PHP MongoDB 创建集合

PHPMongoDB 创建创建集合可以使用下面的代码

<?php
/*
* filename: main.php
* author: pottercoding.cn 程序员波特,程序员编程资料站(pottercoding.cn)
* Copyright © 2015-2065 pottercoding.cn. All rights reserved.
*/
$m = new MongoClient(); // 连接
$db = $m->souyunku; // 切换到 "souyunku" 数据库
$c_lession = $db->createCollection("lession"); // 创建 lession 集合
echo "集合创建成功\n";

运行以上 PHP 脚本,输出结果如下:

$ php main.php
集合创建成功

PHP MongoDB 插入文档

可以使用 insert() 方法向 lession 集合中插入文档

<?php
/*
* filename: main.php
* author: pottercoding.cn 程序员波特,程序员编程资料站(pottercoding.cn)
* Copyright © 2015-2065 pottercoding.cn. All rights reserved.
*/
$m = new MongoClient(); // 连接
$db = $m->souyunku; // 切换到 "souyunku" 数据库
$collection = $db->lession; // 选择集合
$document = array
(
    "title" => "MongoDB 基础教程",
    "favorite" => 1580000,
    "url" => "https://pottercoding.cn/l/penglei/mongodb/",
    "by" => "penglei"
);
$collection->insert($document);
echo "数据插入成功\n";