OPTIONS
翻译或纠错本页面

Authenticate to a MongoDB Instance or Cluster

概述

To authenticate to a running mongod or mongos instance, you must have user credentials for a resource on that instance. When you authenticate to MongoDB, you authenticate either to a database or to a cluster. Your user privileges determine the resource you can authenticate to.

You authenticate to a resource either by:

  • using the authentication options when connecting to the mongod or mongos instance, or
  • connecting first and then authenticating to the resource with the authenticate command or the db.auth() method.

This section describes both approaches.

In general, always use a trusted channel (VPN, SSL, trusted wired network) for connecting to a MongoDB instance.

Prerequisites

You must have user credentials on the database or cluster to which you are authenticating.

Procedures

Authenticate When First Connecting to MongoDB

1

Specify your credentials when starting the mongo instance.

When using mongo to connect to a mongod or mongos, enter your username, password, and authenticationDatabase. For example:

mongo --username "prodManager" --password "cleartextPassword" --authenticationDatabase "products"
2

Close the session when your work is complete.

To close an authenticated session, use the logout command.:

db.runCommand( { logout: 1 } )

Authenticate After Connecting to MongoDB

1

Connect to a MongoDB instance.

Connect to a mongod or mongos instance.

2

Switch to the database to which to authenticate.

use <database>
3

Authenticate.

Use either the authenticate command or the db.auth() method to provide your username and password to the database. For example:

db.auth( "prodManager", "cleartextPassword" )
4

Close the session when your work is complete.

To close an authenticated session, use the logout command.:

db.runCommand( { logout: 1 } )