如何连接 php7 和 mongoDB

How to connect php7 with mongoDB

我正在尝试将 PHP 7 连接到 mongoDB,我按照此 page 说明使用 pecl 安装了 "new" MongoDB 驱动程序。我可以从 phpInfo() 输出中看到 MongoDB 版本 1.1.8,但我不知道如何从 PHP 代码 :p 启动连接。以下代码包括我的连接尝试(甚至使用旧时尚方式尝试连接)

// new fashion way
$connection = new MongoDB\Driver\Client();

// or by using old fashion way
$conn = new MongoClient();

// random try :p
$randConn = new MongoDB\Client();

在这两种情况下,我都遇到了未定义 class 异常。 请让我知道我遗漏了什么以及我的错误在哪里,如果可能的话请提供和示例以便更容易理解;)。

PS:使用的操作系统是 ubuntu 14.04 LTS。


提前致谢。

您所指的页面是 MongoDB 的低级 PHP 驱动程序。 API 与 HHVM driver for MongoDB. The documentation for both of them is the same, and can be found at http://docs.php.net/manual/en/set.mongodb.php

相同

驱动程序被编写为与 MongoDB 通信的基本层,因此缺少许多便利功能。取而代之的是,这些方便的方法被拆分成写在PHP、MongoDB Library 中的一层。使用此库应该是您与 MongoDB.

交互的 首选 方式

库需要安装 Composer, a package manager for PHP. See also Get Composer: Installation on Linux/OSX

例如:

composer require "mongodb/mongodb=^1.0.0"

安装后,您可以尝试使用以下方式连接:

<?php
 require 'vendor/autoload.php';
 $collection = (new MongoDB\Client("mongodb://127.0.0.1:27017"))->dbname->coll;
?>

另请参阅: