1 min read

Mongodb handy commands

Mongodb command collection for user management

Connect

1
mongosh --host localhost:27017 -u admin -p xxxxxxxx --authenticationDatabase admin

User management

Create

1
2
3
4
5
db.createUser({
  user: "username",
  pwd: "password",
  roles: [{ role: "readWrite", db: "database" }],
});

Update

1
2
3
db.updateUser("username", {
  pwd: "password",
});

Delete

1
db.dropUser("username");

Change Password

1
db.changeUserPassword("username", "password");

Privileges

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
db.createRole({
  role: "readSpecificCollections",
  privileges: [
    {
      resource: { db: "my_database", collection: "products" },
      actions: ["find"],
    },
    {
      resource: { db: "my_database", collection: "inventory" },
      actions: ["find"],
    },
  ],
  roles: [],
});