MongoDB Quickstart from Beginner to Expert at Lightning Speed

Sudarsanam Bharath
12 min readMar 5, 2024

Introduction

In the rapidly evolving world of data management, the choice between SQL and NoSQL databases has become a pivotal decision for developers and businesses alike. With the advent of big data, the limitations of traditional relational databases began to emerge, paving the way for the rise of NoSQL databases, designed to handle vast amounts of unstructured data with ease. Among the frontrunners in this revolution is MongoDB, a NoSQL database known for its flexibility, scalability, and performance. In this blog post, we embark on a journey to not only master MongoDB but also to understand the fundamental differences between NoSQL and SQL databases.

Differences Between NoSQL and SQL

The debate between NoSQL and SQL databases is not just about choosing different types of databases; it’s about selecting a data management philosophy that aligns with the needs of your application. Here are the key differences:

  1. Data Structure: SQL databases use structured, table-based formats, requiring predefined schemas. NoSQL databases, like MongoDB, offer flexible data models (documents, key-value pairs, etc.), accommodating unstructured or semi-structured data.
  2. Scalability: SQL databases typically scale vertically, requiring more powerful hardware for expansion. NoSQL databases are designed for horizontal scalability, spreading data across multiple servers easily.
  3. Query Language: SQL databases utilize the Structured Query Language (SQL) for data manipulation, which is highly standardized and powerful for complex queries. NoSQL databases employ a variety of simpler, often more intuitive query languages tailored to their specific data model.
  4. Consistency and Transactions: SQL databases follow ACID properties for transactions, ensuring data integrity and consistency. NoSQL databases may prioritize availability and partition tolerance (CAP theorem), leading to eventual consistency models.
  5. Use Cases: SQL is preferred for applications needing complex transactions and strict data integrity with a fixed schema, such as banking systems. NoSQL shines in scenarios requiring rapid scaling, flexible schema design, and varied data types, like big data analytics and content management systems.

NoSQL Environment

What we’re dealing with here is a No-SQL database. Now, No-SQL is an acronym that stands for ‘Not Only Structured Query Language’. This implies that it incorporates more than just the traditional SQL methods of handling data. In fact, it diverges quite significantly from traditional databases that organize data into rows and columns like a spreadsheet.

In a No-SQL database, the storage and retrieval of data is handled in a fundamentally different manner. Instead of rows and columns, data is stored in the form of key-value pairs or graphs, which are collectively termed ‘documents’. MongoDB, being document-oriented, stores data in JSON-like documents (BSON format), allowing for nested structures and arrays.

Now, these documents are not just floating around in the database. They are organized into what is known as a ‘collection’. A collection is essentially a group of documents, much like a folder on your computer. This allows for easier management and retrieval of related documents. But it doesn’t stop there. Collections themselves are grouped together into what is called a ‘Database’. This is the highest level of organization in a No-SQL database, containing one or more collections.

One of the most popular examples of a No-SQL database is MongoDB. MongoDB exemplifies the principles and functionalities of No-SQL databases, making it a popular choice among developers and businesses alike.

Installation of MongoDB

This guide will walk you through three different methods available for installing the software.

Terminal Console

  • The first method involves using the terminal console, a text-based interface where you can input commands directly to perform specific tasks.
  • Follow the guide to install the MongoDB Shell -> https://www.mongodb.com/try/download/shell

SDK Extension

  • The second method is through the SDK Extension. This is a set of development tools that allow developers to create applications for specific software packages.
  • Follow the guide to install the MongoDB SDK along with a code editor like VSCode -> https://code.visualstudio.com/docs/azure/mongodb

Management Console — Compass

  • The third method is through the Management Console which is also known as Compass. This is a user interface that allows users to manage and monitor their applications.
  • Follow the guide to install the MongoDB Compass -> https://www.mongodb.com/try/download/compass

Moving onto the topic of databases

  • If you’d like to see all available databases that are at your disposal, you would execute the commandshow dbs. This command will provide a comprehensive list of all databases present in the system.
show dbs
  • In the event that you want to utilize an existing database or if you have the need to create a new one, the command to use would be use database_name. Here replace database_name with your preferred name for the database. This command allows you to either start working with an existing database or create a new one if the specified database does not exist.
use database_name
  • Finally, in the subsequent section, you will see a practical implementation of all the CRUD operations. CRUD stands for Create, Read, Update, and Delete. These operations form the basis of any data-driven application and are essential for manipulating data.

MongoDB Collections

  • In MongoDB, collections are used to organize and store data. If you want to view all the collections in your database, you simply use the command show collectionsThis will display a list of all the collections you have.
show collections
  • When it comes to creating a new collection, you can use the db.createCollections()function.
db.createCollections()
  • To create a new collection, you can use the command db.createCollection("name",{capped:true,size:1000*1024,max:100},{autoIndexId:false}). This command will create a new collection with the specified name. The options inside the curly braces indicate that the collection is capped to a certain size, and set a maximum number of documents that the collection can hold. The autoIndexId:false option specifies that MongoDB will not create an index on the _id field automatically.
db.createCollection("name",{capped:true,size:1000*1024,max:100},{autoIndexId:false})
  • Lastly, if you need to delete a collection, the command db.collectionname.drop() can be used. This command will drop or delete the specified collection from the database.
db.collectionname.drop()

Inserting

  • To insert a single document into the database, you can utilize the insertOne method as follows: db.collectionName.insertOne({name: 'Name', id: 'ID'}). This will allow you to add an individual record with the specified name and id values.
db.collectionName.insertOne({name: 'Name', id: 'ID'})
  • If you wish to insert multiple documents at once, the insertMany method is available. The syntax is as follows: db.collectionName.insertMany([{name: 'Name1', age: 'Age1', gpa: 'GPA1'}, {name: 'Name2', age: 'Age2'}]). This command will insert several documents with various properties into the database.
db.collectionName.insertMany([{name: 'Name1', age: 'Age1', gpa: 'GPA1'}, {name: 'Name2', age: 'Age2'}, {}])
  • After running these insert operations, you will be given a result which should look something like this: {acknowledged: 'true', id:ObjectId('682364862386')}. This indicates that the operation was successful and provides you with the ObjectId of the inserted document(s).
{acknowledged: 'true', id:ObjectId('682364862386')}
  • If you want to view all the documents that were inserted, you can use the find method. By typing db.collectionName.find(), all the documents within the specified collection will be printed out for you to review.
db.collectionName.find()

Datatypes

In the domain of computer science and data management, datatypes are an integral and fundamental concept. These represent the type of data that can be processed or manipulated in a computer program. They dictate the operations that can be performed on the data, the meaning of the data, and the way values of that type can be stored. The following are the basic datatypes in MongoDB.

  • String: This data type refers to a sequence of characters, which can be words or sentences enclosed within single and double quotes. A string can contain alphanumeric characters, including numbers and letters.
  • Integer: This represents non-decimal numbers, essentially whole numbers that can be either positive, negative, or zero.
  • Double: This data type is used to represent decimal numbers, providing a way to store numbers with fractional parts.
  • Boolean: It represents logical entities. It can have one of two possible values — true or false.
  • Date: This built-in data type is used to store dates and times. It’s typically created using the ‘new Date()’ function.
  • Null: It represents a variable that has no value assigned to it. Essentially, it shows that the variable exists, but it doesn’t contain any value or object.
  • Array: This is a data type that can store a field of values. For instance, an array can store multiple strings such as [” biology”,” chemistry”,” calculus”]. It’s a collection of similar types of elements.
  • Nested Document: This is a document within a document, often used for storing more complex data structures like addresses and other nested information.

Detailed Explanation on Sorting and Limiting in MongoDB

In this context, the term “name” is representative of the name of the collection within a database.

  • Use db.name.find().sort({fieldname: num}) to sort the documents in a collection.
db.name.find().sort({fieldname: num})
  • For sorting in alphabetical order or ascending order, use the sort parameter as 1 (num: 1).
db.name.find().sort({fieldname: 1})
  • To sort in reverse alphabetical order or descending order, use the sort parameter as -1 (num: -1).
db.name.find().sort({fieldname: -1})
  • If you want to limit the results of your query, use db.name.find().limit(1). This will return the first document that matches the query.
db.name.find().limit(1)
  • If you’re interested in getting the document with the highest value for a particular field, use db.name.find().sort({fieldname: num}).limit(num). This command sorts the documents in descending order (assuming 'num' is set to -1) and limits the result to the desired number of documents.
db.name.find().sort({fieldname: num}).limit(num)

Understanding the Find Method

In this context, the term “name” is representative of the name of the collection within a database.

  • The ‘find’ method in MongoDB, is represented as db.name.find({query},{projection})functions similarly to the WHERE clause in SQL. This method allows you to query your database for specific documents.
db.name.find({query},{projection})

For instance, if you want to find a document where the name is ‘Patrick’ and the GPA is ‘98’, you would use the query db.name.find({name:'patrick',gpa:98}) .If there are no documents that match this query, the find method will not return anything.

db.name.find({name:'patrick',gpa:98})
  • The ‘projection’ parameter in the find method is used to specify which fields to return in the documents that match the query. By default, the find method returns all fields in the matched documents.

However, you can use projection to return only the fields you need. For example, if you only want to return the ‘name’ field for documents where ‘gpa’ is ‘10’, you can use the query db.name.find({gpa:10},{name: true}). Here, ‘true’ or ‘1’ means to include the ‘name’ field in the returned documents.

db.name.find({gpa:10},{name: true })

If you want to exclude the ‘_id’ field from the returned documents, you can do so by using ‘_id: false’ or ‘0’ in the projection parameter.

db.name.find({name:'patrick',gpa:98},{_id: false})

Updating Documents

  • The command db.name.updateOne(filter,update) is used to update one document in the collection that matches the filter.
db.name.updateOne(filter,update)
  • The ‘filter’ parameter is used to select the document to be updated. This selection is based on the criteria defined within the filter.
  • Here’s an example,db.name.updateOne({name:'Spongebob'},{$set:{fullTime:true}}) . This command will search for a document where the name is “Spongebob” and set the ‘fullTime’ field to true.
db.name.updateOne({name:'Spongebob'},{$set:{fullTime:true}})
  • If you want to update a document using its unique ID, you can use the command db.name.updateOne({_idObjectId('45425h2b3')},{$set:{fullTime:false}}). This will find the document with the specified ID and set the ‘fullTime’ field to false.
db.name.updateOne({_idObjectId('45425h2b3')},{$set:{fullTime:false}})
  • You also have the option to completely remove a field from a document. This can be done using the cmd db.name.updateOne({_idObjectId()},{$unset:{fullTime:''}}). Here, the ‘fullTime’ field is completely removed.
db.name.updateOne({_idObjectId()},{$unset:{fullTime:''}})
  • If you want to make a blanket update to many documents at once, you can use the db.name.updateMany({},{$set:{fullTime:false}}). This command sets the ‘fullTime’ field to false for all documents in the collection.
db.name.updateMany({},{$set:{fullTime:false}})
  • If you want to assign the ‘fullTime’ field for documents where it doesn’t exist, you can use db.name.updateMany({fullTime:{$exists: false}},{$set:{fullTime:false}}) .This command checks if the ‘fullTime’ field exists and if it doesn’t, it assigns it a value of false.
db.name.updateMany({fullTime:{$exists: false}},{$set:{fullTime:false}})

Deleting documents from a MongoDB database

  • In this context, the term “name” is representative of the name of the collection within a database.
  • To delete a single document that matches a certain condition, you can make use of the deleteOne function. For instance, if you wanted to delete a document in the ‘name’ collection where the ‘name’ field is an empty string, you would use the following command: db.name.deleteOne({name:""}).
db.name.deleteOne({name:""})
  • If you want to delete multiple documents that match a certain condition, you would use the deleteMany function. For instance, if you wanted to delete all documents in the ‘name’ collection where the ‘fullTime’ field is not specified, you would use the following command: db.name.deleteMany({fullTime: }).
db.name.deleteMany({fullTime: })
  • If you want to delete documents where a certain field does not exist, you would use the delete function with the $exists operator. For instance, if you wanted to delete all documents in the ‘name’ collection where the ‘registerDate’ field does not exist, you would use the following command: db.name.delete({registerDate:{$exists:false}}).
db.name.delete({registerDate:{$exists:false}})

Operators in MongoDB

Comparison Operators in MongoDB

  • The concept of comparison operators: In MongoDB, comparison operators are used to compare values in a database. They are usually represented with a $ sign.
  • The functionality of comparison operators: These operators return results based on the comparison of values. For instance, they can be used to find documents where the value of a certain field matches a condition.
  • Example of ‘Not Equal To’ operator: For instance, to find documents where the ‘name’ field is not equal to ‘SpongeBob’, we would use the ‘$ne’ operator like so: db.name.find({name:{$ne:'SpongeBob'}}).
db.name.find({name:{$ne:'SpongeBob'}})
  • Example of ‘Less Than’ operator: Similarly, to find documents where the ‘age’ field is less than 20, we would use the ‘$lt’ operator like so: db.name.find({age:{$lt:20}}).
db.name.find({age:{$lt:20}})
  • Other comparison operators: Besides ‘$ne’ and ‘$lt’, there are other comparison operators used in MongoDB. These include ‘$lte’ (less than or equal to), ‘$gt’ (greater than), ‘$gte’ (greater than or equal to), ‘$in’ (matches any value in an array), and ‘$nin’ (matches none of the values in an array).
  • Example of ‘In’ operator: To find documents where the ‘name’ field matches either ‘pooja’ or ‘likitha’, we would use the ‘$in’ operator like so: db.name.find({name:{$in:["pooja","likitha"]}}).
db.name.find({name:{$in:["pooja","likitha"]}})
  • Nin’ operator: The ‘$nin’ operator works just like the ‘$in’ operator, but in reverse. It matches documents where the field value is not in the specified array.

Logical operators in MongoDB

  • ‘and’ operator: This is used when you want to filter documents that satisfy both conditions. For instance, you can find all full-time employees who are 23 or younger with the following command: db.name.find({$and:[{fulltime:},{age:{$lte:23}}]}).
db.name.find({$and:[{fulltime:},{age:{$lte:23}}]})
  • ‘or’ operator: This is used when you want to filter documents that satisfy one or both conditions. For instance, you can find all full-time employees or those who are 23 or younger with the following command: db.name.find({$or:[{fulltime:},{age:{$lte:23}}]}).
db.name.find({$or:[{fulltime:},{age:{$lte:23}}]})
  • ‘nor’ operator: This is used when you want to filter documents that do not satisfy both conditions. For instance, you can find all documents that are neither related to full-time employees nor those who are 23 or younger with the following command: db.name.find({$nor:[{fulltime:},{age:{$lte:23}}]}).
db.name.find({$nor:[{fulltime:},{age:{$lte:23}}]})
  • ‘not’ operator: This is used when you want to filter documents that do not satisfy a condition. For instance, you can find all employees who are not 30 or older with the following command: db.name.find({age:{$not:{$gte:30}}}).
db.name.find({age:{$not:{$gte:30}}})

Understanding Indexes

Indexes are used to quickly locate data without having to search every row in a database table every time a database table is accessed. They can be compared to an index at the end of a book.

  • To swiftly locate a specific field within a document, you can use the ‘find’ function. For example, to find the document with the name “Larry”, you would use the following command: db.name.find({name:”Larry”}).explain(”executionStats”).
db.name.find({name:"Larry"}).explain("executionStats")
  • To create an index, you can use the ‘createIndex’ function. The following command would create an index on the ‘name’ field: db.name.createIndex({name:1}).
db.name.createIndex({name:1})
  • After creating the index, you can again use the ‘find’ function to fetch the document with the name “Larry” and explain the execution stats. Here’s how you would do it: db.name.find({name:”Larry”}).explain(”executionStats”).
db.name.find({name:"Larry"}).explain("executionStats")
  • To get a list of all the indexes that you have in your database, you can use the ‘getIndexes’ function. Here’s how: db.name.getIndexes().
db.name.getIndexes()
  • If you need to drop an index, you can use the ‘dropIndex’ function. The following command would drop the index on the ‘name’ field: db.name.dropIndex(”name_1”).
db.name.dropIndex("name_1")

Conclusion

MongoDB exemplifies the NoSQL database model by offering a flexible, schema-less environment for data storage and manipulation. Its support for various data types, powerful querying capabilities, and scalability make it a popular choice for modern applications dealing with large volumes of diverse data. Whether through the terminal, SDKs, or graphical interfaces like Compass, MongoDB caters to developers with different preferences and needs, facilitating efficient data management and application development. As we continue to navigate the vast landscape of data management, the decision to use NoSQL or SQL should not be seen as a binary choice but rather as an opportunity to leverage the unique strengths of each according to the demands of your applications. Whether you’re building complex financial systems, managing large-scale content, or analyzing big data, the right database solution is out there. The key is to assess your needs carefully, consider the trade-offs, and choose the technology that best fits your vision for the future.

Additional Information

Training Access: MongoDB University offers comprehensive courses for each pathway, providing the foundational knowledge and advanced skills needed to excel using different developer pathways like c#, python, java, PHP, etc. To know more and access MongoDB training refer to -> https://learn.mongodb.com/catalog

Certification Exam: Priced at $150, but students with the GitHub Student Developer Pack can take it for free, offering a great opportunity to gain a recognized credential without cost on credly. Also, the non-students can avail of a discount coupon of 50% on the certification exam price upon completing any of the developer pathways at MongoDB University. There are 3 different certification exams you can take:

  1. MongoDB Certified Associate Developer
  2. MongoDB Certified Associate Database Administrator
  3. MongoDB Certified Associate Data Modular

To know more and access MongoDB certifications refer to -> https://learn.mongodb.com/pages/certification-program

Benefits: Certification from MongoDB enhances your resume, opens new career opportunities, and connects you with a global community of MongoDB professionals.

Thanks to everyone who read this blog. Your curiosity is greatly appreciated. Let’s explore the future of No-SQL together! Before you go:

--

--

Sudarsanam Bharath

Technology, Astrophysics, and Open Source Contributions all the time. Fitness buff & athlete with a record of 13km jog in 85 mins #itookcs50