Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Tuesday 20 February 2024

GRANT and REVOKE in MongoDB

In MongoDB, you manage access control using user roles and privileges. The GRANT and REVOKE commands as seen in relational databases like MySQL or PostgreSQL aren't directly available. Instead, you grant privileges to users through role assignments.


 Creating Roles and Assigning Privileges:


To grant privileges in MongoDB, you typically follow these steps:


1. Create a Role: Define a role with the desired privileges.

2. Assign Role to User: Assign the role to a specific user or users.


 Example:


Let's say you want to grant read and write access to a database named mydatabase and its collection mycollection to a user named myuser.


1. Create Role:


db.createRole({

   role: "readWriteMyDatabase",

   privileges: [

     { resource: { db: "mydatabase", collection: "mycollection" }, actions: [ "insert", "update", "remove", "find" ] }

   ],

   roles: []

})



2. Assign Role to User:


db.grantRolesToUser("myuser", ["readWriteMyDatabase"])


This will grant the user myuser the necessary permissions to perform read and write operations on mycollection within the mydatabase.


 Revoking Privileges:


Revoking privileges in MongoDB is done by removing the role assignment from the user.


db.revokeRolesFromUser("myuser", ["readWriteMyDatabase"])


This will remove the role readWriteMyDatabase from the user myuser.


Remember, MongoDB doesn't support the fine-grained control of privileges at the level of individual documents or fields within documents. Privileges are generally granted at the database or collection level. Always ensure to grant only the necessary permissions to maintain the security of your MongoDB database.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.