Skip to main content

How to create users in MongoDB

Assuming you've already completed the basic setup process mentioned in this blog. In this example, we'll see how we can create admin user and enable authorization.

Connect to admin database

On a cmd window, connect to MongoDB by hitting command "mongo". By default, it connects to "test" database.
Once connection is successful, switch to admin db

#mongo
#use admin

Create Role

After switching to admin db, create executiveFunction role
db.runCommand({ createRole: "executeFunctions",
  privileges: [
    { resource: { anyResource: true }, actions: [ "anyAction" ]  }
  ],
  roles: [],
  writeConcern: { w: "majority" , wtimeout: 5000 }
});

Create admin user

In this step, we'll create admin user mongoadmin with password mongo123
db.runCommand( 
    { 
        "createUser" : "mongoadmin", 
        "pwd": "mongo123", 
        "customData" : 
                {"description": "mongo admin user" }, 
                "roles" : 
                    [ 
                        {
                            "role" : "executeFunctions",
                            "db" : "admin"
                        }, 
                        "root"
                    ] 
    },
    { 
        w: "majority",
        wtimeout: 5000
    } 
);

Create readonly user

For guest access on your database, you may want to create readonly users as well. In this example below, we are creating role "readonly" with "read" access on database "mydb"
#switch to mydb    
use mydb
    db.grantRolesToUser(
        "readonly",
        [
          { role: "read", db: "mydb" }
        ]
    )

Now let's create a user "mongoread" with password "read0nly" on db "mydb"
db.runCommand( 
    { 
        "createUser" : "mongoread", 
        "pwd": "read0nly", 
        "customData" : { "description": "mongo readonly user" }, 
        "roles" : 
            [ 
                {
                    "role" : "read",
                    "db" : "mydb"
                }
            ] 
    },
    { w: "majority" , wtimeout: 5000 } 
);

Enable security on your database

Now, you're all set to enable security on your database. Open mongod.conf and change the value of security.authorizationEnabled attribute to "enabled"
systemLog:
    destination: file
    path: M:\mongodb\data\log\mongod.log
storage:
    dbPath: M:\mongodb\data\db
net:
    bindIp: 127.0.0.1
security:
    authorization: enabled
Remove mongod service to install the service again with new parameters
mongod --remove

Reinstall the service
mongod --config "M:\mongodb\conf\mongod.cfg" --serviceName "MongoDB" --serviceDisplayName "MongoDB" --serviceDescription "MongoDB Server Instance" --install

That's all!

Comments