MongoDB: Getting started

How to get started with MongoDB

To establish a connection to your MongoDB instance using the Mongo CLI, you can use this command:

mongo --quiet mongodb://<user>:<password>@<XXXXXX>.stackhero-network.com:27017/<database>?tls=true

For instance, if you want to connect as the admin user to the admin database, you could run:

mongo --quiet mongodb://admin:<password>@<XXXXXX>.stackhero-network.com:27017/admin?tls=true

If the Mongo CLI is not installed on your system, you can download it from the official MongoDB documentation. Alternatively, if Docker is available on your system, you might find this command helpful:

docker run -it mongo /bin/bash

To improve security and ensure better organization, it is advisable to create unique users for each database. Here is an example script for creating a new user:

db.getSiblingDB("myDatabase")
  .createUser({
    user: "myUser",
    pwd: "myPassword",
    roles: [ { role: "readWrite", db: "myDatabase" } ],
    passwordDigestor: "server"
  });

The above script creates a user named myUser with the password myPassword, and grants them read and write permissions for the myDatabase database.

Ensure that you are connected as the admin user when performing user creation operations.

To remove a user, such as myUser, from the myDatabase database, you can execute the following command:

db.getSiblingDB("myDatabase").dropUser("myUser");

To back up your MongoDB data, you can use the following command:

mongodump --uri "mongodb://<user>:<password>@<XXXXXX>.stackhero-network.com:27017/<database>?tls=true"

If you encounter an error like this:

authentication failed for admin on <database> from client <ip>; UserNotFound: Could not find user admin@<database>

It could be due to the admin user not being registered for the specified database. Adding the --authenticationDatabase=admin option might resolve the issue:

mongodump --authenticationDatabase=admin --uri "mongodb://<user>:<password>@<XXXXXX>.stackhero-network.com:27017/<database>?tls=true"

For a compressed backup, you can include the --gzip option:

mongodump --gzip --uri "mongodb://<user>:<password>@<XXXXXX>.stackhero-network.com:27017/<database>?tls=true"

This error might arise when attempting to create a user via the Admin Mongo UI. To avoid this, use the Mongo query provided in the creating databases and users in MongoDB section.

Note: The Admin Mongo UI does not support direct query execution. Instead, you might consider using the Mongo CLI (learn more) or a GUI tool such as Robo 3T (view the configuration guide).