- Connect to MongoDB usingmongosh
To begin working with MongoDB, open your terminal and connect using the MongoDB shell (mongosh):
mongosh
- Create a Database
MongoDB creates databases implicitly when you first store data in them. To switch to (and create) a database:
If you type simply use with any name of database, database will be listed after collection.
use TestDB
- Create a User
Create a user with a username, password, and roles using the db.createUser() command:
db.createUser({
user: “myUser”,
pwd: “myPassword123”,
roles: [
{ role: “readWrite”, db: “TestDB” }
]
})
- Assign Permissions
You can assign multiple roles to a user to grant different levels of access. For example:
db.createUser({
user: “adminUser”,
pwd: “securePass456”,
roles: [
{ role: “readWrite”, db: “TestDB” },
{ role: “dbAdmin”, db: “TestDB” }
]
})
- Authenticate as the Created User
To log in using the newly created user credentials, use the following command:
mongosh -u myUser -p myPassword123 –authenticationDatabase testDB