mongodb 使用 php 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11356834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:20:02  来源:igfitidea点击:

mongodb connect using php

phpmongodb

提问by Rohan Kumar

What if password having @in mongodb connect mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db suppose username='abc'and password='abc@123'and in php we create mongo db instance like

如果有密码@MongoDB中的mongodb连接:// [用户名:密码@]主机1 [:端口1] [,主机2 [:端口2:] ...] / DB假设username='abc'password='abc@123'在PHP中,我们创建一个像蒙戈DB实例

$m = new Mongo('mongodb://[abc:abc@123@]localhost/abc');

then it gives error like this

然后它会给出这样的错误

Fatal error: Uncaught exception 'MongoConnectionException' with message 'couldn't get host info for 123@]localhost'

致命错误:未捕获的异常“MongoConnectionException”,消息为“无法获取 123@]localhost 的主机信息”

then how to solve this type of problem..

那么如何解决这类问题..

回答by Phil

Option 1

选项1

Pass the credentials via the second argument to the Mongoconstructor

通过第二个参数将凭据传递给Mongo构造函数

$db = new Mongo('mongodb://localhost', array(
    'username' => 'abc',
    'password' => 'abc@123',
    'db'       => 'abc'
));

Option 2

选项 2

Use the MongoDB::authenticate()method

使用MongoDB::authenticate()方法

$m = new Mongo();
$db = $m->abc;

$db->authenticate('abc', 'abc@123');

Keep in mind...

记住...

There is a major disadvantage to this method: if the connection is dropped and then reconnects, the new connection will not be authenticated. If you use the URI format, the PHP driver will automatically authenticate the user whenever a new connection is made.

这种方法有一个主要缺点:如果连接断开然后重新连接,则新连接将无法通过身份验证。如果您使用 URI 格式,则每当建立新连接时,PHP 驱动程序都会自动对用户进行身份验证。

2014 Update

2014年更新

Instanciating Mongodirectly is now deprecated. The advice is to use MongoClientinstead with the same arguments as above. For example

Mongo直接实例化现在已被弃用。建议是使用MongoClient与上述相同的参数。例如

$m = new MongoClient('mongodb://localhost', [
    'username' => 'abc',
    'password' => 'abc@123',
    'db'       => 'abc'
]);

回答by Pransh Tiwari

2019 Update

2019年更新

I have used php version 7.0 on ubuntu 16.04. This is a detailed info for solving the connectivity issue. (Skip the parts which you have already done) First I manually installed mongodb and then the mongodb-php driver for it.

我在 ubuntu 16.04 上使用了 php 7.0 版。这是解决连接问题的详细信息。(跳过你已经完成的部分)首先我手动安装了 mongodb,然后为它安装了 mongodb-php 驱动程序。

1) Installing mongo db. Enter the following commands:

1) 安装 mongo db。输入以下命令:

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

$ echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

$ sudo apt-get update

$ sudo apt-get install -y mongodb-org

In order to properly launch Mongdb as a service, ie automatically starting Mongodb when the system starts, follow the following steps:

为了正确启动Mongdb作为服务,即在系统启动时自动启动Mongodb,请按照以下步骤操作:

Create file mongodb.service in /etc/systemd/system/ by entering the command:

通过输入以下命令在 /etc/systemd/system/ 中创建文件 mongodb.service:

$ sudo nano /etc/systemd/system/mongodb.service

Paste the following contents in it:

在其中粘贴以下内容:

[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target

[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target

Then enter the following commands:

然后输入以下命令:

$ sudo systemctl start mongodb

$ sudo systemctl enable mongodb

2) Installing the mongo-php driver:

2) 安装 mongo-php 驱动:

$ sudo pecl install mongodb

Also you might receive error: phpize not found. Phpize is a command which is used to create a build environment. This error could appear at the time of installation of any pecl extension. To solve this problem of the phpize command not found, the user has to install the php5-dev package. To install it enter the command:

您也可能会收到错误:找不到 phpize。Phpize 是一个用于创建构建环境的命令。在安装任何 pecl 扩展时可能会出现此错误。要解决找不到 phpize 命令的问题,用户必须安装 php5-dev 包。要安装它,请输入命令:

 $ sudo apt-get install php7.0-dev

Then in the php.ini file which is in /etc/php/7.0/apache2 directory, add the mongo db extension:

然后在 /etc/php/7.0/apache2 目录下的 php.ini 文件中,添加 mongo db 扩展名:

$ sudo nano /etc/php/7.0/apache2/php.ini 

Add the following line in the file:

在文件中添加以下行:

extension = mongodb.so;

扩展名 = mongodb.so;

(Just so you know, the exact location of the file mongodb.so is in /usr/lib/php/20151012/mongodb.so.)

(正如您所知,文件 mongodb.so 的确切位置在 /usr/lib/php/20151012/mongodb.so 中。)

So the mongo db is installed along with its driver.

因此 mongo db 与其驱动程序一起安装。

3) Now keep in mind that the mongo-php classes have been changed. Most of the available resources in the net give solutions using old classes which is superseded. Below are the links which you can refer to:

3) 现在请记住 mongo-php 类已更改。网络中的大多数可用资源都使用被取代的旧类提供解决方案。以下是您可以参考的链接:

http://php.net/manual/en/set.mongodb.php

http://php.net/manual/en/set.mongodb.php

http://zetcode.com/db/mongodbphp/

http://zetcode.com/db/mongodbphp/

Here are some commands for basic database operations:

下面是一些基本的数据库操作命令:

$mng = new MongoDB\Driver\Manager(); // Driver Object created

To insert data into the database:

向数据库中插入数据:

$bulk = new MongoDB\Driver\BulkWrite;

$doc = ["_id" => new MongoDB\BSON\ObjectID, "data" => $someData, "info" => $someInfo];

$bulk->insert($doc);

$mng->executeBulkWrite('dbName.collectionName', $bulk);

For fetching data:

获取数据:

$query = new MongoDB\Driver\Query([]); 

$rows = $mng->executeQuery("dbName.collectionName", $query);

foreach ($rows as $row) 
    {
         echo "$row->data - $row->info\n";
    }

回答by Pian0_M4n

Using new Mongo();can create problems

使用new Mongo(); 会产生问题

"Warning: Instanciating this class will emit E_DEPRECATED warning, and turn off acknowledged writes." - php.com

“警告:实例化此类将发出 E_DEPRECATED 警告,并关闭已确认的写入。” - php.com

Use MongoClient() insted

使用 MongoClient() 插入

$m = new MongoClient("mongodb://testUser:testPass@localhost:myportnumber");