Skip to main content

Command Palette

Search for a command to run...

A Comprehensive Guide to MongoDB

An overview of MongoDB, its versatility as a NoSQL database, and its functionalities for handling data.

Updated
4 min read
A Comprehensive Guide to MongoDB

Introduction

MongoDB is a versatile NoSQL database that provides a wide array of functionalities for handling data. This blog post is derived from comprehensive notes and includes insights from various sources to help you understand the essentials of MongoDB, from setting up databases to performing complex queries and optimizations.

Setting Up MongoDB

To start with MongoDB, follow these basic steps:

  1. Install MongoDB: You can download and install MongoDB from its official website.

  2. Start MongoDB Server: Use the command mongosh to start the MongoDB server.

  3. Connect to MongoDB: Open a new terminal and use the command mongo to connect to the MongoDB server.

Basic Commands

Listing Databases

To list all databases, use:

show dbs

Selecting a Database

To switch to a specific database:

use database_name

Showing Collections

To show all collections in the current database:

show collections

Printing Documents

To print documents in a collection:

db.collection_name.find().pretty()

Creating Databases and Collections

Creating a Database

MongoDB creates a new database implicitly when you create a collection within it:

use new_database
db.createCollection("new_collection")

Inserting Documents

Single Document

To insert a single document:

db.collection_name.insertOne({ key: value1, key2: value2, key3: value3 })

Multiple Documents

To insert multiple documents:

db.collection_name.insertMany([
  { key1: value1, key2: value2, key3: value3 },
  { key1: value1', key2: value2' }
])

Importing Sample Data

You can import sample datasets from JSON files. Here's how you can do it using MongoDB Compass or terminal commands.

Using MongoDB Compass

  1. Open MongoDB Compass.

  2. Connect to your MongoDB server.

  3. Select the database you want to import data into.

  4. Click on the collection or create a new collection where you want to import the data.

  5. Click on the Add Data button and select Import File.

  6. Choose the JSON or CSV file you want to import and configure the import settings.

  7. Click on Import to load the data into the collection.

Using Terminal Commands

  1. Ensure you have your JSON file ready for import.

  2. Use the mongoimport command to import the data:

     mongoimport --db database_name --collection collection_name --file path_to_your_json_file --jsonArray
    

    For example:

     mongoimport --db myDatabase --collection myCollection --file /path/to/sampleData.json --jsonArray
    

Querying Data

Basic Query

To find documents based on specific criteria:

db.collection_name.find({ key1: value1, key2: value2 })

Projection

To retrieve specific fields from documents:

db.collection_name.find({}, { property1: true, property2: true })

Counting Documents

To count the number of documents in a collection:

db.collection_name.find().count()

Limiting Results

To limit the number of documents returned:

db.collection_name.find().limit(number_of_documents_to_be_shown)

Skipping Documents

To skip a certain number of documents:

db.collection_name.find().skip(n).limit(m)

Filtering and Projections:

  • Filter documents:

      shellCopy codedb.collection_name.find({key1: value1, key2: value2});
    
    • Projection to retrieve specific fields:

        shellCopy codedb.collection_name.find({}, {field1: true, field2: true});
      

Deleting Documents

To delete a document:

db.collection_name.deleteOne({ key: value })

Updating Documents

To update a single document:

db.collection_name.updateOne({ key: value }, { $set: { key: new_value } })

To increment a field:

db.collection_name.updateOne({ key: value }, { $inc: { key: increment_value } })

Advanced Querying

Operators in MongoDB

MongoDB provides various operators for comparison, logical, bitwise, and more:

  • $ne -> not equals

  • $eq -> equals

  • $lt -> less than

  • $lte -> less than or equal to

  • $gt -> greater than

  • $gte -> greater than or equal to

  • $and -> logical AND

  • $or -> logical OR

  • $not -> logical NOT

  • $in -> in array

  • $nin -> not in array

Analyzing Queries

To analyze queries, use the explain function with the executionStats argument:

db.collection_name.find(query).explain("executionStats")

Indexing

Creating Indexes

Indexes improve query performance by organizing data efficiently:

db.collection_name.createIndex({ key: 1 })

Listing Indexes

To list all indexes in a collection:

db.collection_name.getIndexes()

Removing Indexes

To remove an index:

db.collection_name.dropIndex("index_name")

Analyzing Indexes

Before and after creating an index, you can analyze the query execution time:

db.collection_name.find(query).explain("executionStats")

MongoDB Use Cases

MongoDB for Chats

  • Flexible schema

  • Scalable

  • Easy backup using import-export

  • No ACID transactions required

RDBMS for Payments

  • High ACID compliance required

  • Transaction capabilities

  • Strict schema

  • Normalizations and joins

Conclusion

MongoDB is a powerful NoSQL database with a wide array of functionalities for managing data efficiently. From basic operations like inserting and querying documents to advanced features like indexing and query optimization, MongoDB provides robust tools for developers. This guide offers a comprehensive overview to get you started and enhance your skills in using MongoDB effectively.

Happy coding!

More from this blog

Santosh's blog

17 posts