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

Saturday, 3 February 2024

How to create User in MongoDB

To create a user in MongoDB, you can follow these steps using the MongoDB shell:


1. Connect to MongoDB:

   - Open a MongoDB shell or connect to your MongoDB server.


2. Switch to the Admin Database:

   - User administration is typically performed on the "admin" database. Switch to the "admin" database using the `use` command.


     use admin


3. *UseCreate a User:

   - Use the `db.createUser` method to create a new user. Provide a username and password, along with the necessary roles and privileges.

     db.createUser({

       user: 'your_username',

       pwd: 'your_password',

       roles: [

         { role: 'readWrite', db: 'your_database_name' },

         // Add more roles if needed

       ]

     }) 


   - Replace `'your_username'` and `'your_password'` with the desired username and password for the new user. Adjust the `roles` array to grant specific privileges to the user.


4. Verify User Creation:

   - You can verify that the user has been created by switching to the admin database and running the `show users` command.

     use admin

     show users


   - Alternatively, you can query the `system.users` collection:

     db.system.users.find()


This process creates a user with the specified roles and privileges. Ensure that you choose roles that align with the required permissions for the user. If you want to create a user for a specific database, switch to that database using the `use` command before running the `db.createUser` method.


Remember to use strong and secure passwords, especially in production environments.

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