Lesson 3: Connecting to MongoDB Servers / Learn
Code Summary: Connecting to MongoDB Servers
Review the following code, which demonstrates how to connect to the MongoDB Shell, or mongosh, on a new mongod instance and use mongosh database methods.
Connect to mongosh
Start the mongod service:
sudo systemctl start mongod
Connect to mongosh on the default port:
mongosh
Create the First admin Database User
Switch to the admin database:
use admin
Use the createUser() method with the username set to "dbaTestAdmin", password set to "dbaTestPassword", and role set to 'root':
db.createUser(
{
user: "dbaTestAdmin",
pwd: "dbaTestPassword",
roles: [ { role: 'root', db: 'admin' } ]
}
)
To see the database users, run the following command:
show users
Use db.adminCommand()
To create the first admin database user, use the db.adminCommand() method:
db.adminCommand(
{
createUser: "dbaTestAdmin",
pwd: "dbaTestPassword",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" }
]
}
)
To stop the mongod service by using mongosh, use db.adminCommand(<command>):
db.adminCommand( { shutdown: 1 } )
Use db.help()
To retrieve a list of common mongosh database methods, run the following command:
db.help()