Page Content

Tutorials

How Can I Make MongoDB Authentication Active?

MongoDB Authentication

MongoDB instances must be set up to require client authentication in order to enable authentication. Read and write operations are restricted to authenticated users when security is enabled.

  • The --auth option or enabling authentication in the configuration file are the usual ways to launch the mongod server.
  • MongoDB supports a number of authentication methods, such as Kerberos authentication, LDAP proxy authentication, MongoDB Challenge and Response (MONGODB-CR), X.509 Certificate Authentication, and SCRAM-SHA-1. Replica sets employ keyfile authentication for internal authentication.
  • First User Restriction: In the event that your MongoDB deployment is user-free, you will need to establish the first administrative user by connecting to mongod with either the --noauth option or the localhost exception.

Steps:

Stop the MongoDB instance:

sudo systemctl stop mongod

Edit the MongoDB configuration file:

# mongod.conf
security:
  authorization: enabled

Start the MongoDB instance with the updated configuration:

sudo systemctl start mongod

Connect to MongoDB as a user with administrative privileges:

mongo

Create an administrative user:

use admin;
db.createUser(
  {
    user: "mongoAdmin",
    pwd: passwordPrompt(), // Prompts for password securely
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
);

Exit the mongo shell and reconnect with the new administrative user:

exit
mongo -u mongoAdmin -p --authenticationDatabase admin

Now, all access to your MongoDB server will require authentication.

Exporting Data from MongoDB

Data can be exported from MongoDB in two main ways:

mongodump: This is the suggested tool for backing up your MongoDB database since it exports all of your server’s data in its native BSON format to a dump directory. High fidelity and reliable preservation of all rich BSON data types are guaranteed by mongodump. In addition to providing choices to restrict the quantity of data or backup from a remote server, it can backup a complete server, a specific database, or even a specific collection. Mongodump can also be executed from MongoDB v2.4 when it is connected to a secondary member of a replica set.

Syntax:

mongodump --host HOST_NAME --port PORT_NUMBER --db DB_NAME --collection COLLECTION --out BACKUP_DIRECTORY

Example:

Dump an entire database to a specified directory:

mongodump --db mydatabase --out /path/to/my_backups/2025-07-14_mydatabase_backup

Dump a specific collection:

mongodump --db mydatabase --collection users --out /path/to/my_backups/users_collection_backup

Dump from a remote MongoDB instance with authentication:

mongodump --host remote.mongoserver.com --port 27017 \
          --username adminUser --password MyStrongPassword123 \
          --authenticationDatabase admin \
          --db productionDB --out /path/to/local/backups/productionDB_dump

More Secure (using prompt for password):

mongodump --host remote.mongoserver.com --port 27017 \
          --username adminUser -p \
          --authenticationDatabase admin \
          --db productionDB --out /path/to/local/backups/productionDB_dump

Dump a collection with a specific query:

mongodump --db sales --collection orders \
          --query '{ "status": "completed", "orderDate": { "$gte": ISODate("2024-01-01T00:00:00Z") } }' \
          --out /path/to/my_backups/completed_orders_2024

Dump all databases (excluding local and config) to the current directory:

mongodump

Dump to a single archive file (useful for compression and easier transfer):

mongodump --db mydatabase --archive=/path/to/my_backups/mydatabase_archive.gz --gzip

Dump the oplog (for point-in-time recovery on replica sets):

mongodump --oplog --db mydatabase --out /path/to/my_backups/mydatabase_with_oplog

mongoexport: Data can be exported using mongoexport in commonly supported formats including JSON, CSV, and TSV. Only a subset of the types provided by BSON can be represented by JSON, hence it is unreliable for complete instance production backups. Additionally, mongoexport has the ability to organise the documents using –sort and constrain export data using –skip and –limit parameters.

Example:

Export entire collection to JSON:

mongoexport --db mydb --collection users --out users.json

Export collection to CSV with specific fields:

mongoexport --db mydb --collection products --type=csv --fields name,price,category --out products.csv

Export data with a query filter:

mongoexport --db mydb --collection orders --query '{ "status": "completed" }' --out completed_orders.json

Export from a remote host:

mongoexport --host myremoteserver.com --port 27017 --db mydb --collection sensor_data --out sensor_data.json

Importing Data to MongoDB

mongorestore: This utility is used to recover data from BSON files that mongodump has produced. MongoDB v3.0 requires an active MongoDB instance in order to use mongorestore. Additionally, it can take normal input and convert it to BSON data.

Syntax:

mongorestore [options] <path_to_dump_directory_or_archive_file>

Example:

Restore an entire database from a dump directory:

mongorestore --db mydatabase /path/to/my_backups/2025-07-14_mydatabase_backup/mydatabase

Restore a specific collection:

mongorestore --db mydatabase --collection users /path/to/my_backups/users_collection_backup/mydatabase/users.bson

mongoimport: Data from JSON, CSV, or TSV files can be imported into MongoDB collections using this tool. Because it does not maintain all rich BSON data types, it is unreliable for complete recoveries, much as mongoexport. An array of documents can be given to enable the import of numerous documents.

Syntax:

mongoimport --db <database_name> --collection <collection_name> --file <input_file_name> [options]

Examples:

Import JSON file:

mongoimport --db mydb --collection users --file users.json

Import CSV file with headers:

mongoimport --db mydb --collection products --type=csv --headerline --file products.csv

Import with upsert (update if exists, insert if not):

mongoimport --db mydb --collection users --file new_users.json --upsert --upsertFields email

Import from a remote host:

mongoimport --host myremoteserver.com --port 27017 --db mydb --collection new_data --file new_data.json

Embedded Documents

A record is a document made up of field and value pairs in MongoDB, a document database. Other documents, arrays, and arrays of documents can be the values of fields. This idea makes it possible to represent intricate, rich data structures in a single document and to use flexible schemas.

Advantages: It gives a single object a clear structure and frequently doesn’t require the intricate joins that relational databases frequently require.

Example:

{
  "_id": ObjectId("60c72b2f9b1e8a001c8e1a1b"),
  "name": "Alice Smith",
  "email": "alice@example.com",
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "zip": "90210"
  },
  "orders": [
    {
      "orderId": "ORD001",
      "date": ISODate("2023-01-15T10:00:00Z"),
      "items": [
        { "product": "Laptop", "quantity": 1, "price": 1200 },
        { "product": "Mouse", "quantity": 1, "price": 25 }
      ]
    },
    {
      "orderId": "ORD002",
      "date": ISODate("2023-03-20T14:30:00Z"),
      "items": [
        { "product": "Keyboard", "quantity": 1, "price": 75 }
      ]
    }
  ]
}

In this example, address is an embedded document, and orders is an array of embedded documents.

Query Embedded Documents Using Mongo Shell

Dot notation is used by MongoDB to query fields inside embedded documents.

Example:

Find users from a specific city:

db.users.find({ "address.city": "Anytown" });

Find users with a specific street and state:

db.users.find({ "address.street": "123 Main St", "address.state": "CA" });

Find orders that contain a specific product:

db.users.find({ "orders.items.product": "Laptop" });

Find users who have an order placed after a certain date:

db.users.find({ "orders.date": { $gt: ISODate("2023-02-01T00:00:00Z") } });

Using $elemMatch for querying array of embedded documents when multiple conditions apply to a single array element:

// Find users who have an order with product "Laptop" AND quantity 1
db.users.find({
  "orders.items": {
    $elemMatch: {
      product: "Laptop",
      quantity: 1
    }
  }
});

Create User and Add Role in MongoDB

MongoDB manages user privileges through role-based access control.

  • Creating a User: Users are made in a particular database, which serves as their authentication database. A new user can be created using the db.createUser() method.
    • Exampleuse admin; db.createUser({ user: "superuser", pwd: "12345678", roles: [ "root" ] }); This creates a superuser in the admin database with the root role, which grants all privileges.
  • Roles and Privileges:
    • Roles are groups of privileges, defining actions a user can perform.
    • MongoDB provides built-in roles such as read, readWrite, dbAdmin, userAdmin, dbOwner, clusterManager, clusterMonitor, hostManager, and clusterAdmin.
    • You can also create custom roles using db.createRole().
    • To assign roles to a user, use db.grantRolesToUser().

In Conclusion:

Cross-platform and document-oriented, MongoDB provides easy scalability, high availability, and great performance. It is one of the top NoSQL databases and is written in C++. Text search, MapReduce, atomic operations, relationships, database references, covered queries, advanced indexing, and GridFS are all addressed in advanced MongoDB concepts.

Index