📜  mongodb list users - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:32:56.594000             🧑  作者: Mango

MongoDB List Users - Shell/Bash

MongoDB provides a command to list all users in a database. This command can be executed using the MongoDB Shell or a Bash script.

Using MongoDB Shell

To list all users in a MongoDB database using the MongoDB Shell, follow these steps:

  1. Open MongoDB Shell
  2. Switch to the database you want to list users for using the use command, like so: use mydatabase
  3. Run the db.getUsers() command to list all users in the database.
use mydatabase
db.getUsers()

This will return a list of all users in the database, including their username and roles.

Using Bash Script

You can also list all users in a MongoDB database using a Bash script. Here is an example:

#!/bin/bash

MONGODB_URI=mongodb://localhost:27017/mydatabase

mongo ${MONGODB_URI} << EOF
use mydatabase
db.getUsers()
EOF

This script defines the MongoDB URI and then executes the db.getUsers() command using the mongo shell.

Expected Output:

[
  {
    "_id": "mydatabase.admin",
    "user": "admin",
    "db": "mydatabase",
    "roles": [
      {
        "role": "readWrite",
        "db": "mydatabase"
      },
      {
        "role": "dbAdmin",
        "db": "admin"
      }
    ],
    "mechanisms": [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
    ]
  }
]

This will return the same list of users as the MongoDB Shell command.

In conclusion, being able to list all users in a MongoDB database is important for database administrators to ensure proper access controls and security measures are in place. This can be achieved using both MongoDB Shell and Bash scripts.