无法使用php连接到mongodb数据库用户 [英] Cant connect to a mongodb database user with php

查看:245
本文介绍了无法使用php连接到mongodb数据库用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器上运行的是auth=true的mongod.

I've a running mongod with auth=true on my server.

如果我从管理数据库登录到管理员用户,则获取数据没有问题.

If I log to my admin user (from the admin database), no problem to fetch data.

<?php
$connection = new Mongo("mongodb://admin:adminpass@127.0.0.1");

$db = $connection->selectDB( "mydb" );
$collection = $db->selectCollection( "user" );
var_dump($collection->findOne());
?>

但是如果我将第一行替换为

but if I replace the first line by

$connection = new Mongo("mongodb://mydbadmin:dbadminpass@127.0.0.1:27017");

它无法连接并出现错误:

It can not connect and get an error like :

Fatal error: Uncaught exception 'MongoConnectionException' with message 'Couldn't authenticate with database admin: username [mydbadmin]' in .....

所以问题是new Mongo()尝试将我的用户连接到admin数据库而不是"mydb"数据库.如何选择要连接的数据库?

So the problem is new Mongo() try to connect my user to the admin database instead of the "mydb" database. How can I choose the database I want to connect?

根据 http://php.net/manual/fr/mongo.construct进行. php
我尝试过了

according to http://php.net/manual/fr/mongo.construct.php
I tried this

$login = array("username" => "mydbadmin",
               "password" => "dbadminpass",
               "db" => "mydb",
               "connect" => true
);

$connection = new Mongo("mongodb://localhost", $login);

但是

Couldn't authenticate with database mydb: username [mydbadmin]' in .....

推荐答案

好吧,如果您未在构造函数中指定db,则默认情况下它将使用admin数据库(如

Well if you don't specify a db in the constructor, it uses the admin database by default (as documented in the Mongo::__construct-reference). Try the following:

$connection = new Mongo("mongodb://admin:adminpass@127.0.0.1/mydb");

在主机部分之后注意/mydb,它使PHP-api连接到所需的数据库.

notice the /mydb after the host-part, which lets the PHP-api connect to the desired database.

这篇关于无法使用php连接到mongodb数据库用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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