如何将php7与mongoDB连接 [英] How to connect php7 with mongoDB

查看:222
本文介绍了如何将php7与mongoDB连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将PHP 7与mongoDB连接,我通过遵循页面说明.我可以从phpInfo()输出中看到MongoDB版本1.1.8,但是我不知道如何从PHP代码:p发起连接.以下代码包括我的连接尝试(即使使用旧的方式也尝试连接)

I'm trying to connect PHP 7 with mongoDB, I installed the "new" MongoDB driver using pecl by following this page instructions. I can see MongoDB version 1.1.8 from phpInfo() output, but I can't figure out how to initiate a connection from PHP code :p . the following code includes my attempts to connect (tried to connect even using old fashion way)

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

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

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

,在两种情况下,我都未定义类异常. 请让我知道我想念的是什么,我的错误在哪里,请提供示例,以便在可能的情况下更易于遵循;).

and in both cases, I'm getting not defined class exception. please let me know what I'm missing and where is my mistake, please provide and example to be easier to follow if possible ;) .

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

PS: used operating system is ubuntu 14.04 LTS.

提前谢谢.

推荐答案

您所引用的页面是MongoDB的低级PHP驱动程序.该API与用于MongoDB的HHVM驱动程序相同.两者的文档都相同,可以在 http://上找到docs.php.net/manual/en/set.mongodb.php

The page that you are referring to is the low-level PHP driver for MongoDB. The API is the same as the 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库.使用该库应该是与MongoDB进行交互的首选方法.

The driver is written to be a bare bone layer to talk to MongoDB, and therefore misses many convenience features. Instead, these convenience methods have been split out into a layer written in PHP, the MongoDB Library. Using this library should be your preferred way of interacting with MongoDB.

该库需要使用PHP的软件包管理器 Composer 进行安装.另请参见获取Composer:在Linux/OSX上安装

The library needs to be installed with Composer, a package manager for PHP. See also Get Composer: Installation on Linux/OSX

例如:

composer require "mongodb/mongodb=^1.0.0"

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

Once you have it installed, you can try connecting using:

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

另请参阅:

  • Doc: MongoDB PHP Library
  • MongoDB PHP Library: Getting Started
  • PHP MongoDB Driver

这篇关于如何将php7与mongoDB连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆