Operations with MongoDB accounts via the CLI

Authorization

For authorization when interacting with the DBMS via the console interface, the parameters are passed to mongo

  1. --authenticationDatabase <the database used for authorization>
  2. -u <user name>
  3. -p <password>

example:

mongo --authenticationDatabase admin -u admin -p 123

Create a user

To create a user, you must have the dbOwner role, or the UserAdmin role in the database that is used for authorization (for example, admin), and in all the databases where roles are added, or the createUser command privilege in this database and the grantRole command privileges in databases where roles are added.

A user is created through the console interface by the command

mongo --eval "(new Mongo()).getDB(<имя бд, куда писать данные авторизации>').createUser( \
{ \
  user: '<пользователь>', \
  pwd: '<пароль>', \
  roles: [ \
    { role: 'readWrite', db: '<бд куда доступ на чтение-запись>' }, \
    { role: 'read', db: '<бд где только чтение>' }, \
    { role: 'write', db: '<бд где только запись>' } \
  ]})"

example:

mongo --eval "(new Mongo()).getDB('admin').createUser( \
{ \
  user: 'admin', \
  pwd: '123', \
  roles: [ \
    { role: 'readWrite', db: 'admin' }, \
    { role: 'readWrite', db: 'config' }, \
    { role: 'readWrite', db: 'local' } \
  ]})"

or in one line

mongo --eval "(new Mongo()).getDB('admin').createUser({user: 'demo',pwd: '123',roles: [{ role: 'readWrite', db: 'admin' },{ role: 'readWrite', db: 'config' },{ role: 'readWrite', db: 'local' }]})"

Delete a user

To delete a user, you must have the dbOwner role, or have the UserAdmin role or the dropUser command privilege in the database that is used for authorization, for example, admin.

Delete a user through the CLI mongodb with the command

mongo --eval "(new Mongo()).getDB('<бд с данными авторизации>').dropUser('<имя>')"

example:

mongo --eval "(new Mongo()).getDB('admin').dropUser('demo')"