Php uses uri mode to connect mongodb, does not have the right to restrict normal connection, if you have permission, it will fail.

mongodb can be connected through php connection without permission authentication, and the data can be read out.

$con = new MongoClient();
//

but after adding user rights authentication, it keeps prompting fatal error, authentication failed, etc., that the user name and password are correct and do not have permission.

$con = new MongoClient("mongodb://test:test123@localhost:27017/phptest");

this sentence has been connected incorrectly.
but you can connect through the client

> mongo phptest -u test -p test123

so that you can read and write normally.

Mar.02,2021

according to the introduction of mongo uri in the official document , the database, specified after uri is used to specify the authorization database, not the database selected after a successful connection.

/ database : Optional. The name of the database to authenticate if the connection string includes authentication credentials in the form of username:password@. If / database is not specified and the connection string includes credentials, the driver will authenticate to the admin database.

needs to specify the authorization database because the authorization database is not always named admin , which is just the name that most people will name, and the authorization database name that mongo will connect to by default. It is also possible for you to name the authorization database test , then you need to specify the authorization database as test : mongo://user:pass@localhost:27017/test .

back to your question, your authorization library should not be called phptest . Remove the database name and you should be able to connect successfully. After the connection is successful, then use MongoClient to select the library. Php's mongo syntax is still super simple:

$mongo_client->phptest
Menu