DEV Community

Cover image for The Ultimate MongoDB Configuration Cheatsheet: Tips and Commands
Sidali Assoul
Sidali Assoul

Posted on • Originally published at blog.spithacode.com

The Ultimate MongoDB Configuration Cheatsheet: Tips and Commands

Introduction to MongoDB

Overview

MongoDB is a leading NoSQL database that provides high performance, high availability, and easy scalability. Unlike traditional SQL databases, MongoDB uses a flexible, schema-less data model, making it ideal for handling unstructured data.

Key Features

  • Scalability: Easily scale horizontally with sharding.
  • Flexibility: Schema-less design allows for diverse data models.
  • High Performance: Efficiently handles large volumes of data.
  • Rich Query Language: Powerful querying and aggregation capabilities. ## Configuration Notes ### Exporting Data Exporting data in MongoDB can be done in different formats like BSON and JSON. Here are some essential commands and their use cases. ## Exporting a Database in BSON ### Command Syntax To export a database in BSON format, use the following command:
mongodump --uri \"mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/<database_name>\"
Enter fullscreen mode Exit fullscreen mode

Benefits of BSON

BSON is a binary representation of JSON-like documents, providing faster performance and easy parsing compared to JSON. It is ideal for backup and restoration tasks due to its efficiency.

Exporting a Collection in JSON

Command Syntax

To export a specific collection in JSON format, use this command:

mongoexport --uri=\"mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/<database_name>\" --collection=<collection_name> --out=<output_file_name>.json
Enter fullscreen mode Exit fullscreen mode

Use Cases for JSON

JSON is human-readable and easy to edit, making it suitable for data exchange and debugging purposes. It's also useful for integration with other systems that support JSON.

Importing Data

Importing data into MongoDB can also be done using BSON or JSON formats, depending on your requirements.

Restoring from a BSON Database File

Command Syntax

To restore from a BSON database file, use the following command:

mongorestore --uri \"mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/<database_name>\" --drop dump
Enter fullscreen mode Exit fullscreen mode

Practical Example

Using BSON for restoration ensures that the data is imported efficiently and correctly, maintaining the original structure and indexes of the database.

Importing a Collection as a JSON File

Command Syntax

To import a collection from a JSON file, use this command:

mongoimport --uri=\"mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/<database_name>\" --drop <file_collection_name>.json
Enter fullscreen mode Exit fullscreen mode

Specifying Collection Names

If you need to specify a different collection name than the file name, use this command:

mongoimport --uri=\"mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/<database_name>\" --drop <file_collection_name>.json --collection <collection_name_different_then_file_name>
Enter fullscreen mode Exit fullscreen mode

MongoDB Terminologies

Understanding Namespace

In MongoDB, a namespace refers to the concatenation of the database name and the collection name. This unique identifier helps in organizing and accessing the data efficiently.

MongoDB Commands

General Commands

MongoDB provides a variety of commands to interact with databases and collections. These commands allow you to perform CRUD operations, manage indexes, and run aggregations.

Database Related Commands

Switching Databases

To switch to a specific database, use the following command:

use <database_name>
Enter fullscreen mode Exit fullscreen mode

Listing Collections

To list all collections in the current database, use:

show collections
Enter fullscreen mode Exit fullscreen mode

Database Commands Syntax

You can execute commands on collections using the following syntax:

db.<collection_name>.<command_name>
Enter fullscreen mode Exit fullscreen mode

Insertion Commands

InsertOne

To insert a single document into a collection, use:

db.<collection_name>.insertOne({...data})
Enter fullscreen mode Exit fullscreen mode

InsertMany

To insert multiple documents, use:

db.<collection_name>.insertMany([{...data},....,{...data}])
Enter fullscreen mode Exit fullscreen mode

BulkWrite

For bulk operations, use:

db.<collection_name>.bulkWrite(...params)
Enter fullscreen mode Exit fullscreen mode

Count Documents in a Collection

Using countDocuments

To count the number of documents in a collection, use:

db.<collection_name>.countDocuments({...filter})
Enter fullscreen mode Exit fullscreen mode

Find Commands

find

To find documents in a collection, use:

db.<collection_name>.find({...filter},{...projection})
Enter fullscreen mode Exit fullscreen mode

findOne

To find a single document, use:

db.<collection_name>.findOne({...filter},{...projection})
Enter fullscreen mode Exit fullscreen mode

Update Commands

updateOne

To update a single document, use:

db.<collection_name>.updateOne({...filters},{...operators})
Enter fullscreen mode Exit fullscreen mode

updateMany

To update multiple documents, use:

db.<collection_name>.updateMany({...filters},{...operators})
Enter fullscreen mode Exit fullscreen mode

bulkWrite

For bulk update operations, use:

db.<collection_name>.bulkWrite(...params)
Enter fullscreen mode Exit fullscreen mode

Return Distinct Field Values

Using distinct

To get distinct values of a field, use:

db.<collection_name>.distinct(<field_name>)
Enter fullscreen mode Exit fullscreen mode

Delete/Drop Commands

deleteMany

To delete multiple documents, use:

db.<collection_name>.deleteMany({...filter})
Enter fullscreen mode Exit fullscreen mode

deleteOne

To delete a single document, use:

db.<collection_name>.deleteOne({...filter})
Enter fullscreen mode Exit fullscreen mode

drop

To drop a collection, use:

db.<collection_name>.drop()
Enter fullscreen mode Exit fullscreen mode

Filter Operators

Basic Comparison Operators

Use comparison operators for filtering data:

db.<collection_name>.findOne({age:{\"$gt\":17}})
db.<collection_name>.findOne({age:{\"$gte\":17}})
db.<collection_name>.findOne({age:{\"$lt\":17}})
db.<collection_name>.findOne({age:{\"$lte\":17}})
db.<collection_name>.findOne({age:{\"$ne\":17}})
db.<collection_name>.findOne({age:{\"$in\":[10,20,30,40]}})
Enter fullscreen mode Exit fullscreen mode

Logical Operators

Use logical operators for complex queries:

db.routes.find({ \"$and\": [ { \"$or\" :[ { \"dst_airport\": \"KZN\" }, { \"src_airport\": \"KZN\" } ] }, { \"$or\" :[ { \"airplane\": \"CR2\" }, { \"airplane\": \"A81\" } ] } ]})
Enter fullscreen mode Exit fullscreen mode

exists Operator

To check if a field exists:

db.collectionName.find({fieldName:{$exists:true}})
Enter fullscreen mode Exit fullscreen mode

Regular Expressions

For pattern matching:

db.collectionName.find({ 'login' :{ '$regex' : '^a.m', '$options':'i'}}, {\"_id\": 0,\"name\": 1,\"login\": 1})
Enter fullscreen mode Exit fullscreen mode

Array Operators

For array filtering:

db.users.find({things:{'$elemMatch':{t:2}}})
db.collectionName.find({jobs.1:'java'})
Enter fullscreen mode Exit fullscreen mode

Post Search Methods

sort

To sort query results:

db.collectionName.sort(\"fieldName\")
db.collectionName.sort({fieldName1:1,fieldName2:-1})
Enter fullscreen mode Exit fullscreen mode

limit and offset

For pagination:

db.collectionName.sort(\"fieldName\").skip(5).limit(20)
Enter fullscreen mode Exit fullscreen mode

count

To count documents:

db.users.find().count()
Enter fullscreen mode Exit fullscreen mode

Update Operators

set

To set field values:

db.users.updateMany({},{\"$set\":{dumyyyyyyyyyyyyyyyy:50}})
Enter fullscreen mode Exit fullscreen mode

inc

To increment field values:

db.updateOne({name:\"sidali\"},{'$inc':{age:17}})
Enter fullscreen mode Exit fullscreen mode

unset

To remove fields:

db.users.updateMany({}, { $unset: { fieldName: \"\" } })
Enter fullscreen mode Exit fullscreen mode

Array Mutation Methods

push

To add items to an array:

db.users.updateMany({},{\"$push\":{arrayName:\"item\"}})
db.users.updateMany({},{$push:{arrayName:{$each:[\"item1\",\"item2\",\"item3\"]}}})
Enter fullscreen mode Exit fullscreen mode

Insertion Tricks

Multiple Insertions

Insert multiple documents in order:

db.inspections.insert([ { \"test\": 1 }, { \"test\": 2 }, { \"test\": 3 } ])
Enter fullscreen mode Exit fullscreen mode

Ordered Insertions

Insert multiple documents with ordered option:

db.inspections.insert([{ \"_id\": 1, \"test\": 1 },{ \"_id\": 1, \"test\": 2 }, { \"_id\": 3, \"test\": 3 }],{ \"ordered\": false })
Enter fullscreen mode Exit fullscreen mode

Aggregation Framework

match

For filtering documents:

db.users.aggregate([ {$match:{age:{$gt:18}}}, {$project:{name:1,\"address.city\":1}}, {$sort:{name:1,\"address.city\":-1}} ])
Enter fullscreen mode Exit fullscreen mode

project

To include or exclude fields:

db.users.aggregate([ {'$unwind' : \"$job\"}, {'$project' : {'_id':0, \"login\" : 1, \"age\" : 1, \"job\":1}} ])
Enter fullscreen mode Exit fullscreen mode

sort

To sort aggregation results:

db.collectionName.aggregate([ {'$match': {\"address.city\" : \"sba\"}}, {'$unwind' : \"$job\"}, {'$group' : {\"_id\" : \"$job\", \"moy\": {'$avg': \"$age\"}} }, {'$match' : {\"moy\" : {'$gt' : 10}} }, {'$sort' : { \"moy\" : -1} } ])
Enter fullscreen mode Exit fullscreen mode

unwind

To deconstruct arrays:

db.collectionName.aggregate([ {'$unwind' : \"$job\"}, {'$project' : {'_id':0, \"login\" : 1, \"age\" : 1, \"job\":1}} ])
Enter fullscreen mode Exit fullscreen mode

group

To group documents and perform aggregations:

db.collectionName.aggregate([ {\"$group\":{\"_id\":\"$type\",\"avg_nb_pages\":{\"$avg\":{\"$subtract\":[\"$pages.end\",\"$pages.start\"]}}}} ])
Enter fullscreen mode Exit fullscreen mode

lookup

To join documents from different collections:

db.users.aggregate([ {'$lookup': {'from': \"comments\", 'localField': \"_id\", 'foreignField': \"userid\", 'as': \"commentdetails\"} } ])
Enter fullscreen mode Exit fullscreen mode

Indexing

Creating Indexes

To create a single field index:

db.trips.createIndex({ \"birth year\": 1 })
Enter fullscreen mode Exit fullscreen mode

Unique Indexes

For creating unique indexes:

db.trips.createIndex({ \"birth year\": 1 }, { unique: true })
Enter fullscreen mode Exit fullscreen mode

Compound Indexes

To create a compound index:

db.trips.createIndex({ \"start station id\": 1, \"birth year\": 1 })
Enter fullscreen mode Exit fullscreen mode

FAQs

How do I export a MongoDB database?
To export a MongoDB database in BSON format, use the mongodump command with the appropriate URI.
How can I import data into MongoDB?
Use the mongorestore command for BSON files or mongoimport for JSON files to import data into MongoDB.
What commands are essential for MongoDB operations?
Key commands include insertOne, find, updateOne, deleteMany, and various aggregation commands like match, project, and group.
How do I insert multiple documents at once?
Use the insertMany command to insert multiple documents into a collection.
What is the aggregation framework in MongoDB?
The aggregation framework allows for advanced data processing and analysis through pipelines like $match, $group, and $sort.
How do I create indexes in MongoDB?
Use the createIndex command to create single field or compound indexes for optimizing query performance.

Conclusion

MongoDB offers a robust set of features and commands that enable efficient data management. By mastering the configuration notes, export/import commands, and various MongoDB commands, you can harness the full potential of MongoDB for your data needs. Whether it's performing CRUD operations, using advanced filters, or optimizing queries with indexes, this guide provides the comprehensive knowledge required to excel in MongoDB usage.

Top comments (0)