Learn MongoDB in One Shot - Ultimate MongoDB Guide
Tags: mongodb, webdev, beginners, tutorial
Published: 2023-07-24 23:43:02

> Update: This article is featured in Official MongoDB Newsletter
Read full newsletter [here 🔗](https://email.mongodb.com/e/evib?_t=86ba93b39a0e415ea7cd8e8ed81051cd&_m=4192b82bdf1f463b9a369bc7a56da9dd&_e=7yRBq78yS_LSVijz5O-_s6zjbYpHpVH8hYhUiKEJElWuHMWZPWSUzeBIR_YhvSOc)

![Newsletter Screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1yegrh1wymv0o3rfvu5.png)

<br />
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...](https://www.mongodb.com/basics/scaling))
    
* **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...*](https://www.mongodb.com/advantages-of-mongodb)

## 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.
    
    ```json
    { 
        "_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](https://www.mongodb.com/docs/manual/administration/install-community/) and [MongoDB Shell](https://www.mongodb.com/docs/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:

```js
db.users.insertOne({
  name: "John",
  age: 30
})
```

![Insert Document Terminal Screenshot](https://cdn.hashnode.com/res/hashnode/image/upload/v1689974232923/8ec4a5f5-a8ca-428c-b2bb-1c959effe22d.png)

To insert multiple documents:

```js
db.users.insertMany([
  {name: "John", age: 30},
  {name: "Jane", age: 27}
])
```

![Insert Document Terminal Screenshot](https://cdn.hashnode.com/res/hashnode/image/upload/v1689975349062/82ad729a-9265-4883-8a71-9ae3290bfff6.png)

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()`:

```javascript
db.users.find({}) // returns all documents
```

Specify a query filter object to select matching documents:

```js
db.users.find({age: {$gt: 18}}) // age greater than 18
```

![Document Operation Demo Terminal Screenshot](https://cdn.hashnode.com/res/hashnode/image/upload/v1689973335353/f8651af6-8e3f-4cb3-b7cd-83c0eab558b4.png)

![Document Operation Demo Terminal Screenshot](https://cdn.hashnode.com/res/hashnode/image/upload/v1689973468418/262c7274-2d1e-4a51-a6c5-1443f6aaa1f3.png)

Common query operators:

* Comparison (`$eq`, `$gt`, `$lt`)
    
* Logical (`$and`, `$or`, `$not`)
    
* Evaluation (`$exists`, `$type`)
    
* Array (`$in`, `$nin`)
    

![Document Operation Demo Terminal Screenshot](https://cdn.hashnode.com/res/hashnode/image/upload/v1689975466096/962218c3-b903-4d8c-bc5e-73100b4b196b.png)

[Read more about query operators here...](https://www.mongodb.com/docs/manual/reference/operator/query/)

### 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1689971869868/d2670481-659f-4c3d-9caa-b60c3e99f0c7.png)

```js
db.users.find({}, {name: 1, email: 1}) // only return name and email
```

### Sorting

Pass a sort specifier to `sort()`:

```js
db.users.find({}).sort({age: -1}) // sort by age descending
db.users.find({}).sort({age: 1}) // sort by age ascending
```

### Limiting

Limit results with `limit()`:

```js
db.users.find({}).limit(10) // only return 10 docs
```

### Pagination

Use cursor for skipping and limiting:

```js
const cursor = db.users.find()
cursor.skip(10).limit(10) // skip 10, limit 10
```

There are many more querying capabilities - covered later!

## Updating Documents

Use update operators like `$set` to update documents:

```js
db.users.update({name: "John"}, {$set: {age: 20}})
```

![Document Operation Demo Terminal Screenshot](https://cdn.hashnode.com/res/hashnode/image/upload/v1689973772405/9b719ce9-7cb3-4304-9a57-9106d3d52420.png)

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()`:

```js
db.users.deleteMany({status: "inactive"})
```

## Indexes

<mark>Advanced Topic Alert</mark>

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:

```js
db.users.find({name: "John"})
db.users.find({name: {$gt: "A"}})  
db.users.find({}).sort({name: 1}) // sort by name ascending
```

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:

```js
db.users.createIndex({name: 1}) // Ascending index
```

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&gt;&gt;&gt;[https://www.mongodb.com/docs/manual/indexes/](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 💖