To authenticate a client in MongoDB, you must add a corresponding user to MongoDB.
User Management
You can add a user with the db.createUser() method using
mongosh. The first user you create must have privileges
to create other users. The userAdmin or
userAdminAnyDatabase role both confer the privilege to
create other users.
You can grant a user privileges by assigning roles to the user when you create the user. You can also grant or revoke roles and update passwords by updating existing users. For a full list of user management methods, see User Management.
Authentication Database
The database where you add a user is its authentication database.
A user's privileges are not limited to their authentication database and can span multiple databases. For more information on roles, see Role-Based Access Control in Self-Managed Deployments.
A user's name and authentication database serve as a unique identifier
for that user. MongoDB associates a user with a unique userId upon
creation in MongoDB. However, LDAP managed users
created on an LDAP server do not have an associated document in the
system.users collection, and
therefore don't have a userId field
associated with them.
If two users have the same name but are created in different databases, they are two separate users. If you want to have a single user with permissions on multiple databases, create a single user with a role for each applicable database.
Centralized User Data
MongoDB stores all user information, including name, password, and the user's authentication
database, in the system.users collection in the admin
database.
Do not modify this collection directly. To manage users, use the designated user management commands.
Sharded Cluster Users
To create users for a sharded cluster, connect to a
mongos instance and add the users. To authenticate as a
user created on a mongos instance, you must authenticate
through a mongos instance.
In sharded clusters, MongoDB stores user configuration data in the
admin database of the config servers.
Shard Local Users
Some maintenance operations, such as cleanupOrphaned,
compact, or rs.reconfig(), require direct
connections to specific shards in a sharded cluster. To perform these
operations, you must connect directly to the shard and authenticate as a
shard local administrative user.
To create a shard local administrative user, connect directly to the primary of the shard and create the user. For instructions on how to create a shard local user administrator see the Keyfile Authentication for Self-Managed Sharded Clusters tutorial.
MongoDB stores shard local users in the admin database of the
shard itself. These shard local users are independent from
the users added to the sharded cluster through a mongos.
Shard local users are local to the shard and are inaccessible by
mongos.
Direct connections to a shard should only be used for shard-specific
maintenance and configuration. In general, clients must connect to the sharded
cluster through the mongos.