Introduction
Creating users and roles helps control who can access your database and what they can do. It keeps your data safe and organized.
db.createUser({
user: "username",
pwd: "password",
roles: [
{ role: "roleName", db: "databaseName" }
]
})
// To create a role:
db.createRole({
role: "roleName",
privileges: [
{
resource: { db: "databaseName", collection: "collectionName" },
actions: ["action1", "action2"]
}
],
roles: []
})db.createUser() to add a new user with specific roles.db.createRole() to define a custom role with specific privileges.db.createUser({
user: "readerUser",
pwd: "readerPass",
roles: [ { role: "read", db: "myDatabase" } ]
})db.createUser({
user: "adminUser",
pwd: "adminPass",
roles: [ { role: "dbAdmin", db: "myDatabase" } ]
})db.createRole({
role: "customReadWrite",
privileges: [
{
resource: { db: "myDatabase", collection: "myCollection" },
actions: ["find", "insert", "update"]
}
],
roles: []
})use myDatabase
db.createRole({
role: "limitedEditor",
privileges: [
{
resource: { db: "myDatabase", collection: "products" },
actions: ["find", "update"]
}
],
roles: []
})
db.createUser({
user: "editorUser",
pwd: "editorPass",
roles: [ { role: "limitedEditor", db: "myDatabase" } ]
})sales database in MongoDB?db.createUser() with roles as an array of objects specifying role and database.db.createUser({user: 'adminUser', pwd: 'secure123', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]})adminUser have?userAdminAnyDatabasedb.createUser({user: 'testUser', pwd: 'test123', roles: ['readWrite']})role and db fields, not just strings.reportViewer that allows users to only read data from the reports collection in the analytics database. Which command correctly creates this role?Pass the test and this pattern moves unknown