DEV Community

Cover image for Learn MongoDB in One Shot - Ultimate MongoDB Guide
MohitSinghChauhan
MohitSinghChauhan

Posted on • Updated on • Originally published at mohitdotexe.hashnode.dev

Learn MongoDB in One Shot - Ultimate MongoDB Guide

Update: This article is featured in Official MongoDB Newsletter
Read full newsletter here 🔗

Newsletter Screenshot



MongoDB is a popular open-source NoSQL document database. It stores data in flexible JSON-like documents rather than tables with a fixed schema like SQL databases. MongoDB makes it easy to store and query large volumes of unstructured or semi-structured data.

Why Use MongoDB?

Some key advantages of MongoDB:

  • Flexible schema - Documents can have varying sets of fields, allowing you to store different types of data in the same collection.

  • Scalability - MongoDB scales horizontally using sharding to support high volumes of reads and writes. (Read more here...)

  • Performance - The document storage model allows for faster queries compared to relational databases. Indexes and in-memory caching provide further performance boosts.

  • High availability - Replica sets provide automatic failover and data redundancy.

  • Rich queries - Supports dynamic queries against documents using a document-based query language.

Wants to read all advantages of MongoDB DBMS, check out here...

Key Concepts

Before we jump into using MongoDB, let's understand some key concepts:

  • Document - The basic unit of data in MongoDB. Similar to a row in an RDBMS table. Documents are stored in JSON-like (BSON) format with field-value pairs.

    { 
        "_id": "507f1f77bcf86cd799439011", 
        "name": "Mohit Singh Chauhan", 
        "age": 22
    }
    
  • Collection - A group of documents, similar to a table in RDBMS. A database can have multiple collections.

  • Database - A physical container for collections. Each MongoDB server typically has multiple databases.

Installing MongoDB

I believe you can install it by reading the docs. It is pretty straightforward. You need to install MongoDB Community Server and MongoDB Shell

Follow the links : MongoDB Community Edition and MongoDB Shell,

Set PATH Env Variable for Windows, & Install MongoDB VS Code Extension.

Data Types in MongoDB

MongoDB supports a wide variety of data types for fields in documents:

  • String - UTF-8 encoded string for storing text.

    { name: "John Doe" }

  • Integer - Used for numeric values.

    { age: 25 }

  • Boolean - Stores true/false values.

    { active: true }

  • Double - 64-bit floating point value for decimals.

    { price: 24.99 }

  • Arrays - Stores lists of values in a single key.

    { hobbies: ["football", "chess", "code"] }

  • Embedded Documents - Stores documents inside other documents.

    { address: { street: "123 Main St", city: "New York" } }

  • Object IDs - Special datatype used for document IDs, IDs are autogenerated untill explicitly defined.

    { _id: ObjectId() }

  • Dates - Date and time stored as milliseconds since Unix epoch.

    { createdAt: new Date() }

  • Null - Represents missing or unknown data.

    { middleName: null }

MongoDB provides a flexible schema design allowing documents in a collection to have varying sets of fields.

Inserting Documents

To insert a document into a collection:

db.users.insertOne({
  name: "John",
  age: 30
})
Enter fullscreen mode Exit fullscreen mode

Insert Document Terminal Screenshot

To insert multiple documents:

db.users.insertMany([
  {name: "John", age: 30},
  {name: "Jane", age: 27}
])
Enter fullscreen mode Exit fullscreen mode

Insert Document Terminal Screenshot

MongoDB automatically generates a unique _id field if not provided.

Querying Documents

Use find() to query documents in a collection. It supports:

  • Query filters to select matching documents

  • Projection to return specific fields

  • Sorting

  • Limiting results

  • Cursor for pagination

Query Filters

To return all documents in a collection, pass an empty filter object to find():

db.users.find({}) // returns all documents
Enter fullscreen mode Exit fullscreen mode

Specify a query filter object to select matching documents:

db.users.find({age: {$gt: 18}}) // age greater than 18
Enter fullscreen mode Exit fullscreen mode

Document Operation Demo Terminal Screenshot

Document Operation Demo Terminal Screenshot

Common query operators:

  • Comparison ($eq, $gt, $lt)

  • Logical ($and, $or, $not)

  • Evaluation ($exists, $type)

  • Array ($in, $nin)

Document Operation Demo Terminal Screenshot

Read more about query operators here...

Projection

Specify a projection document to return only selective fields:

_id is true by default so you need to explicitly tell mongosh to not project id

Document Operation Demo Terminal Screenshot

db.users.find({}, {name: 1, email: 1}) // only return name and email
Enter fullscreen mode Exit fullscreen mode

Sorting

Pass a sort specifier to sort():

db.users.find({}).sort({age: -1}) // sort by age descending
db.users.find({}).sort({age: 1}) // sort by age ascending
Enter fullscreen mode Exit fullscreen mode

Limiting

Limit results with limit():

db.users.find({}).limit(10) // only return 10 docs
Enter fullscreen mode Exit fullscreen mode

Pagination

Use cursor for skipping and limiting:

const cursor = db.users.find()
cursor.skip(10).limit(10) // skip 10, limit 10
Enter fullscreen mode Exit fullscreen mode

There are many more querying capabilities - covered later!

Updating Documents

Use update operators like $set to update documents:

db.users.update({name: "John"}, {$set: {age: 20}})
Enter fullscreen mode Exit fullscreen mode

Document Operation Demo Terminal Screenshot

Common update operators:

  • $set - Sets value of a field

  • $inc - Increments value

  • $min/$max - Updates if less/greater than current

  • $push/$pull - Adds/removes from an array

  • $rename - Renames a field

Deleting Documents

To delete documents, use deleteOne() or deleteMany():

db.users.deleteMany({status: "inactive"})
Enter fullscreen mode Exit fullscreen mode

Indexes

Advanced Topic Alert

Indexes allow the MongoDB query engine to quickly find and sort documents by their indexed fields without having to scan every document in the collection.

For example, adding an index on the name field will allow fast lookups like:

db.users.find({name: "John"})
db.users.find({name: {$gt: "A"}})  
db.users.find({}).sort({name: 1}) // sort by name ascending
Enter fullscreen mode Exit fullscreen mode

Without an index on name, these queries would require a full collection scan which can be 100x or more slower on large collections. Indexes make a dramatic impact on performance.

To create an index:

db.users.createIndex({name: 1}) // Ascending index
Enter fullscreen mode Exit fullscreen mode

The index will be created in the background and does not block reads/writes.

Some considerations when using indexes:

  • Indexes consume disk space and memory to store the indexed data efficiently.

  • Adding indexes will slow down write operations like inserts and updates as the indexes also need to be updated.

  • Use indexes judiciously on fields that are frequently queried or sorted on. Avoid over-indexing.

  • Index types like text, geospatial provide additional query capabilities.

  • Compound indexes can be created on multiple fields.

Summing Up, Indexes allow fast lookups and sorting of documents by indexed fields but also have storage overhead and impact write performance. Use indexes judiciously based on query patterns and system resources.

Read more here>>>https://www.mongodb.com/docs/manual/indexes/

Where To Go From Here

You should now have a solid understanding of the fundamentals of MongoDB. Some recommended next steps to take your MongoDB skills to the next level:

  • Install MongoDB locally and play around with inserting, querying, updating and deleting documents through the MongoDB shell. Hands-on experience is key for mastering MongoDB.

  • Read MongoDB's documentation on aggregation to learn how to perform advanced analytics and data processing on dataset.

  • Learn how to model one-to-one, one-to-many, and many-to-many relationships between documents using embedding and linking.

  • Understand MongoDB's architecture including sharding and replication. Set up a simple sharded cluster.

  • Get started with MongoDB Atlas (MongoDB Cloud Database) to easily spin up a managed MongoDB cluster on the cloud.

  • Learn how to develop applications using MongoDB drivers for languages like Node.js, Java, Python.

  • Explore best practices for data modeling, indexing, and performance optimization when working with MongoDB.

The Mongo community also provides tons of resources to further advance your skills!

Happy Coding 💖

Top comments (6)

Collapse
 
shree675 profile image
Shreetesh M

This is a good article.
MongoDB indexes are a subject on their own. Every developer must know more about indexes to realize their potential and benefits. Do not stop here, as mentioned in the last section.

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

Thanks for reading! You're absolutely correct, After this everyone should check official docs to solidify their understanding on topics that are briefed here, Like you said some topics are subject on their own.

Collapse
 
chiragagg5k profile image
Chirag Aggarwal

Nice article! I have been using mongodb in my ongoing project using NodeJS and it feels really nice to work with. All the tools are really polished and there is documentation for anything you will need.

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

Thanks! MongoDB Documentation is really amazing.

Collapse
 
volodyslav profile image
Volodyslav

Cool article 😁

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

Thanks!