vmware-marketplacemean

Create a MongoDB database and user

Create a database

If you want to install an application manually, it may require the database to be set up first. Use the commands below to create a database. Replace the DATABASE_NAME placeholder with the name of the database you wish to use and the PASSWORD placeholder with your MongoDB password.

$ mongo admin --username root --password PASSWORD
MongoDB shell version: 2.4.8
connecting to: 127.0.0.1:27017/admin
> db = db.getSiblingDB('DATABASE_NAME')
DATABASE_NAME

Create a user with all privileges for a database

To create a user with all privileges for a MongoDB database, select the database for use and then use the createUser() function, as shown below. Replace the DATABASE_NAME placeholder with the name of the database you wish to use, the PASSWORD placeholder with your MongoDB password, and the DATABASE_USER and DATABASE_PASSWORD placeholders with the correct user name and password.

$ mongo admin --username root --password PASSWORD
MongoDB shell version: 2.4.8
connecting to: 127.0.0.1:27017/admin
> db = db.getSiblingDB('DATABASE_NAME')
DATABASE_NAME
> db.createUser( { user: "DATABASE_USER", pwd: "DATABASE_PASSWORD", roles: [ "readWrite", "dbAdmin" ]} )
{
 "user" : "DATABASE_USER",
 "pwd" : "...",
 "roles" : [
  "readWrite",
  "dbAdmin"
 ],
 "_id" : ObjectId("...")
}
> exit

Some applications may require specific privileges in the database. Consult the official installation steps in the application documentation.

Create a user with restricted privileges in an existing database

In case you already have a database created, you can create a new user with restricted privileges. Find an example below of how to create a new user with read-write privileges only. Replace the DATABASE_NAME placeholder with the name of the database you wish to use, and the DATABASE_USER and DATABASE_PASSWORD placeholders with the correct user name and password.

$ mongo admin --username root --password PASSWORD
MongoDB shell version: 2.4.8
connecting to: 127.0.0.1:27017/admin
> db = db.getSiblingDB('DATABASE_NAME')
> db.createUser( { user: "DATABASE_USER", pwd: "DATABASE_PASSWORD", roles: [ "readWrite"]} )
{
   "user" : "DATABASE_USER",
    "pwd" : "...",
     "roles" : [
       "readWrite",
          ],
           "_id" : ObjectId("...")
}
> exit

You can log into an existing database with a non-root user account previously created for it, but you can use that account to create other user accounts only if it has sufficient privileges.

Last modification December 21, 2022