Introduction to MongoDB Authentication

Authentication and authorization are crucial aspects of database security. MongoDB allows you to create and manage users and roles to control access to your databases. In this guide, we'll explore the process of creating and managing MongoDB users and roles, including key concepts and sample code with examples.


Users and Roles

In MongoDB, authentication is managed through users and roles. Here are the key concepts:

  • User: An account with a username and password that can access a database.
  • Role: A set of privileges that define what a user can do within a database.

Creating a MongoDB User

Here's an example of creating a user using the MongoDB shell:


use admin
db.createUser({
user: "myUser",
pwd: "myPassword",
roles: [
{ role: "readWrite", db: "myDatabase" },
{ role: "read", db: "anotherDatabase" }
]
})

Managing Roles

You can assign roles to users to control their privileges. MongoDB provides built-in roles like "read", "readWrite", "dbAdmin", and more. Here's an example of adding a role to an existing user:


use myDatabase
db.grantRolesToUser("myUser", [
{ role: "dbOwner", db: "myDatabase" },
{ role: "readWrite", db: "anotherDatabase" }
])

Authentication and Connection

To connect to MongoDB with authentication, you need to specify the username and password in your connection string. Here's a sample connection string in a Node.js application using the official MongoDB Node.js driver:


const { MongoClient } = require("mongodb");
const uri = "mongodb://myUser:myPassword@localhost:27017/myDatabase";
const client = new MongoClient(uri, { useUnifiedTopology: true });
async function main() {
try {
await client.connect();
const db = client.db();
// Perform database operations
} catch (error) {
console.error("Error:", error);
} finally {
await client.close();
}
}
main();

Conclusion

Managing MongoDB users and roles is essential for controlling access to your databases and ensuring data security. By understanding the concepts of users, roles, and authentication, you can create a secure and well-organized MongoDB environment for your applications.