w3resource

MongoDB: db.auth() method

db.auth()

The db.auth() method is used to authenticates a user to a database.

Syntax:

db.auth()

Allows a user to authenticate to the database from within the shell.

The db.auth() method can accept either:

  • the username and password.
  • db.auth( <username>, <password> )
  • a user document that contains the username and password, and optionally, the authentication mechanism and a digest password flag.
  • db.auth( {
       user: <username>,
       pwd: <password>,
       mechanism: <authentication mechanism>,
       digestPassword: <boolean>
    } )
    

Parameters:

Name Description Required /
Optional
Type
username Specifies an existing username with access privileges for this database. Required string
password Specifies the corresponding password. Required string
mechanism Specifies the authentication mechanism used. Defaults to either:
  • SCRAM-SHA-1 on new 3.0 installations and on 3.0 databases that have been upgraded from 2.6 with authSchemaUpgrade; or
  • MONGODB-CR otherwise.
Optional string
digestPassword Determines whether the server receives digested or undigested password. Set to false to specify undigested password. For use with SASL/LDAP authentication since the server must forward an undigested password to saslauthd. Optional boolean

Alternatively, you can use mongo --username, --password, and --authenticationMechanism to specify authentication credentials.

NOTE: The mongo shell excludes all db.auth() operations from the saved history.

Returns: db.auth() returns 0 when authentication is not successful, and 1 when the operation is successful.

Example: MongoDB: db.auth() method

Assume that A user document for a database that contains the username "mynewuser" and password "myuser123". The following example will authenticate the user for the database.

db.auth( "mynewuser", "myuser123" );

Output:

> db.auth( "mynewuser", "myuser123" );
1

Retrieve the restaurants data from here

Previous: db.version() method
Next: db.createUser() method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/shell-methods/user-management/db-auth.php