How to add user in mongoDB?

Connect with

MongoDBThis article is about how to add user in mongoDB as a admin user and database user.

1. pre-requisite for Adding user in MongoDB

Assuming that following are the assumption before proceeding to the actual stuff.
MongoDB installation ( I have tested on mongodb 3.2 version installed on my server), you can visit my another post, How to install mongoDB in LINUX
MongoDB Auth enabled by SCRAM-SHA-1

2. Add admin user into MongoDB

Add user on admin database:

> use admin
switched to db admin
> db.createUser({"user":"adminUser", "pwd": "secret", "roles": [{"role":"root", "db":"admin"}]});

For simplicity, added a root user on admin database so that root user can perform admin related activity. you can add different role with different database as per your requirement.

3. Add database user into MongoDB

Add database user mongo database, in which you want to use, here ‘myblogdb’ is my database, where I want to auth and insert document.

> use myblogdb
switched to db myblogdb
> db.createUser({"user":"myblogUser", "pwd": "secret", "roles": ["readWrite"]})

for simplicity, added a root user on admin database. you can add different role with different database.

4. Complete Activities on Console

After logged-in into mongodb server, follow the following stuff.

[root@ranjeetJha ~]# mongo

MongoDB shell version: 3.2.1
connecting to: test

> use admin
switched to db admin
> db.auth('adminUser','secret')
1
> db.createUser({"user":"adminUser", "pwd": "secret", "roles": [{"role":"root", "db":"admin"}]})
Successfully added user: {
        "user" : "adminUser",
        "roles" : [
                {
                        "role" : "root",
                        "db" : "admin"
                }
        ]
}
> use myblogdb
switched to db myblogdb
> db.createUser({"user":"myblogUser", "pwd": "secret", "roles": ["readWrite"]})
Successfully added user: { "user" : "myblogUser", "roles" : [ "readWrite" ] }

> use myblogdb
switched to db myblogdb
> db.blog.insert({"title": "how to create user in mongodb"})
WriteResult({ "nInserted" : 1 })
> db.auth('myblogUser','secret')
1
>  db.blog.insert({"title": "how to create and drop user in mongodb"})
WriteResult({ "nInserted" : 1 })
>

5. Drop user from MongoDB

Drop the user from selected database , here myblogdb is db name and myblogUser is username.

> use myblogdb
> db.dropUser('myblogUser')

References
mongoDB official Site


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *