DEV Community

Cover image for A-Z: MongoDB Cheat Sheet­čî▒
Burak Boduro─člu
Burak Boduro─člu

Posted on • Updated on

A-Z: MongoDB Cheat Sheet­čî▒

New Post ­čćĽ

Boost Your Programming Efficiency: Essential Tools for Success ÔÜÖ´ŞĆ
Building a Node.js Server Without Using Express.js­čÉĄ
Dockerizing a Node.js App: A Comprehensive Guide for Easy Deployment­čÉő


Contents ­čôľ


Definitions ­čî│

  • What is MongoDB?

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need.

  • What is a Database?

A database holds a set of collections. A database typically has a separate file system directory to hold its data. Each database gets its own set of files on the file system. Generally, you associate a database with one application.

  • What is a Collection?

A collection is a group of documents. If a document is the MongoDB analog of a row in a relational database table, then a collection is the analog of a table.

  • What is a Document?

A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.

  • What is a Field?

A document has a dynamic schema. Dynamic schemas allow documents in the same collection to have different sets of fields and to have different field names for the common fields.

  • What is a Primary Key?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

  • Why use NoSQL?

NoSQL databases are built to allow the insertion of data without a predefined schema. This makes NoSQL databases ideal for storing and processing unstructured data.

  • Why use MongoDB?

MongoDB is a document database, which means it stores data in JSON-like documents. We believe this is the most natural way to think about data, and is much more expressive and powerful than the traditional row/column model.


MongoDB Shell Commands ­čŹâ­čî▓

  • Show Database
show dbs
Enter fullscreen mode Exit fullscreen mode

This command will show all the databases in your MongoDB server.


  • Use Database
use <database_name>
Enter fullscreen mode Exit fullscreen mode

This command will switch to the database you want to use.


  • Show Collections
show collections
Enter fullscreen mode Exit fullscreen mode

This command will show all the collections in the database you are using.


  • Drop Database
db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

This command will drop the database you are using.


  • Create Collection
db.createCollection("<collection_name>")
Enter fullscreen mode Exit fullscreen mode

This command will create a collection in the database you are using.


  • Insert a Document
db.<collection_name>.insertOne({
    <key>: <value>,
    <key>: <value>,
    ...
})
Enter fullscreen mode Exit fullscreen mode

This command will insert a document in the collection you are using.


  • Insert Multiple Documents
db.<collection_name>.insertMany([
    {
        <key>: <value>,
        <key>: <value>,
        ...
    },
    {
        <key>: <value>,
        <key>: <value>,
        ...
    },
    ...
])
Enter fullscreen mode Exit fullscreen mode

This command will insert multiple documents in the collection you are using.


  • Find Documents
db.<collection_name>.find()
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using.


  • Find Documents with Query
db.<collection_name>.find({
    <key>: <value>
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that match the query.


  • Count Documents
db.<collection_name>.find({
    <key>: <value>
    }).count()
Enter fullscreen mode Exit fullscreen mode

This command will count all the documents in the collection you are using that match the query.


  • Limit Documents
db.<collection_name>.find().limit(<number>)
Enter fullscreen mode Exit fullscreen mode

This command will limit the number of documents returned by the find command.


  • forEach()
db.<collection_name>.find().forEach(function(doc) {
    print("Key: " + doc.<key> + " Value: " + doc.<value>);
})
Enter fullscreen mode Exit fullscreen mode

This command will iterate through all the documents in the collection you are using and print the key and value of each document.


  • Find One Document
db.<collection_name>.findOne({
    <key>: <value>
})
Enter fullscreen mode Exit fullscreen mode

This command will find the first document in the collection you are using that matches the query.


  • Update a Document
db.<collection_name>.updateOne({
    <key>: <value>
}, {
    $set: {
        <key>: <value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will update the first document in the collection you are using that matches the query. $set is used to update the document.


  • Increment a Document
db.<collection_name>.updateOne({
    <key>: <value>
}, {
    $inc: {
        <key>: <value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will increment the value of the key in the first document in the collection you are using that matches the query. $inc is used to increment the value of the key.


  • Delete a Document
db.<collection_name>.deleteOne({
    <key>: <value>
})
Enter fullscreen mode Exit fullscreen mode

This command will delete the first document in the collection you are using that matches the query.


  • Add new field to a Document
db.<collection_name>.updateOne({
    <key>: <value>
}, {
    $set: {
        <new_key>: <new_value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will add a new field to the first document in the collection you are using that matches the query.


  • Greater than
db.<collection_name>.find({
    <key>: {
        $gt: <value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that have a key greater than the value.


  • Greater than or equal to
db.<collection_name>.find({
    <key>: {
        $gte: <value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that have a key greater than or equal to the value.


  • Less than
db.<collection_name>.find({
    <key>: {
        $lt: <value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that have a key less than the value.


  • Less than or equal to
db.<collection_name>.find({
    <key>: {
        $lte: <value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that have a key less than or equal to the value.


  • Not equal to
db.<collection_name>.find({
    <key>: {
        $ne: <value>
    }
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that have a key not equal to the value.


  • And
db.<collection_name>.find({
    $and: [
        {
            <key>: <value>
        },
        {
            <key>: <value>
        }
    ]
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that match the query.


  • Or
db.<collection_name>.find({
    $or: [
        {
            <key>: <value>
        },
        {
            <key>: <value>
        }
    ]
})
Enter fullscreen mode Exit fullscreen mode

This command will find all the documents in the collection you are using that match the query.


  • Sort
db.<collection_name>.find().sort({
    <key>: <value>
})
Enter fullscreen mode Exit fullscreen mode

This command will sort all the documents in the collection you are using by the key.


  • Sort Descending
db.<collection_name>.find().sort({
    <key>: -1
})
Enter fullscreen mode Exit fullscreen mode

This command will sort all the documents in the collection you are using by the key in descending order.


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

This command will drop the collection you are using.


Thank You ­čî┐

Thank you for taking the time to read my blog post! I hope you found it helpful and informative. Your support and engagement mean a lot to me. If you have any questions or feedback, please donÔÇÖt hesitate to reach out. I appreciate your continued interest and look forward to sharing more valuable content in the future. Thank you once again!


References


My other contents


Back to Top

Top comments (26)

Collapse
 
imthedeveloper profile image
ImTheDeveloper

Nice overview. Loved mongo for very simple document storage where there is little to no need to do any complex joins. It can become a beast when needing to use the aggregation pipeline and transformations I've walked into that a couple of times now and wished I'd have stuck to something more relational. My own fault and lesson learnt ­čĄú again though really nice overview and covers so many use cases.

Collapse
 
prsaya profile image
Prasad Saya

The document data of MongoDB is like JSON (plus has more types) and it includes complex types like objects and arrays, often nested to multiple levels (upto 100 levels is possible as per the docs). Working with these complex structures is not always easy. First, the aggregation pipeline syntax is unlike other database querying syntax and there is a learning curve. Attempting aggregation queries on complex data and complex operations without proper learning, the tools and experience is not uncommon - it can create disappointments.

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

­čĄę­čą│

Collapse
 
umakantv profile image
Umakant Vashishtha

This is helpful, I wrote a similar article:
umakantv.medium.com/mongodb-operat... with more types of operators and an example which demonstrates fuzzy text search.

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

Thank you. It looks like helpful.­čśŐ

Collapse
 
prsaya profile image
Prasad Saya

Good effort ­čĹŹ.

I would also include the variations of update and delete methods updateMany and deleteMany. Also, countDocuments is useful.

One of the more useful features of using MongoDB is one can develop applications fast, as it allows quick start and prototyping (for example, I can write application code accessing the database and insert data, query it, etc., without creating a database or a collection, and fields explicitly).

Collapse
 
billernet profile image
Bill­čĺí

Good stuff. We replaced our legacy XML based document format with MongoDB and saw massive speed improvements in loading and querying data. I'm a big proponent of dealing with documents with large volume/size/complexity this way. One thing I would take issue with though is this:

  • Why use MongoDB?

MongoDB is a document database, which means it stores data in JSON-like documents. We believe this is the most natural way to think about data, and is much more expressive and powerful than the traditional row/column model.

While yes, it probably does let you store data in exactly the format that represents the original document, I think it is worth stating that it shouldn't be seen as a wholesale replacement for relational databases. A good rule of thumb is if to use MongoDB or any other document database, and you're finding that the document is starting to contain items which are outside the natural scope of the document to get it to work, it is not a good fit.

Define boundaries for what is stored in the document and be aware of the limitations of relationships between documents.

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

Thanks for sharing this nice comment.­čśŐ

Collapse
 
onlinemsr profile image
Raja MSR

Thank you for sharing this useful MongoDB cheat sheet. I found it very helpful and concise. It covers the most common commands and operations for working with MongoDB databases.

I appreciate your effort and time in creating this resource!

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

­čĹż­čĹĘ­čĆ╗ÔÇŹ­čĺ╗­čÖĆ­čĆ╝

Collapse
 
boly38 profile image
Brice

Good idea ­čĹŹ­čĆ╗

Improvement idea:
From industrialization point of view
When I do update the mongo part of my application I check every possible queries from repository classes and check fields used to build indexes and avoid perf Issues.
You could maybe add a section about indexes and explain plans.

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

Thanks for your recommendation. IÔÇÖm going to add this section. ­čśç

Collapse
 
faisal00121 profile image
Cloudrcm Solutions

Great MongoDB cheat sheet! It's always helpful to have a quick reference guide to assist with common tasks and commands in MongoDB. As someone interested in cloud RCM (Revenue Cycle Management), I can see the potential benefits of integrating MongoDB into cloud-based RCM systems.

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

Thanks for your comment.­čśŐ

Collapse
 
michaeltharrington profile image
Michael Tharrington

Awesome post here, Burak! This is a really helpful and easy-to-read cheat sheet. ­čÖî

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

I am happy to It was useful. Thank you. ­čą│

Collapse
 
layanyashoda profile image
Layan Yasoda

Awesome Post! Thank you.

Collapse
 
adeleyeayodeji profile image
Adeleye Ayodeji

Thank you for the information.

Collapse
 
kumarkalyan profile image
Kumar Kalyan

Great reasource for mongo db :)

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

Thank you :) ­čĹż

Collapse
 
araaranomi profile image
Ara Ara no Mi

I still don't have any usecases for MongoDB, all the data I use ends up being Relational, and I prefer SQL's syntax.

Collapse
 
shree675 profile image
Shreetesh M

This is a good sheet to get a hold on the fundamental commands and operations.

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

­čśç

Collapse
 
vulcanwm profile image
Medea

really helpful!

Collapse
 
burakboduroglu profile image
Burak Boduro─člu

IÔÇÖm glad to hear that. ­čśä

Collapse
 
chiemelie profile image
Chiemelie

The cheat sheet would have gone in an ascending order. Starting with the very basic element in the cheat all the way to the hardest. It makes things easier to understand.