MongoDB for Beginners: A Step-by-Step Guide to Getting Started with NoSQL Database

Muhammad Fahad
6 min readJan 8, 2024

--

MongoDB is a popular and open-source NoSQL database management system that stores data in JSON-like documents. It is designed to handle large amounts of data and provide high performance, scalability and flexibility. MongoDB uses a document-oriented data model which organizes data in collections of JSON-like documents instead of traditional rows and columns in relational databases. This makes MongoDB well-suited for handling unstructured or semi-structured data.

Features of MongoDB

  • Document-Oriented Storage: MongoDB stores data in BSON (Binary JSON) documents which have the flexibility to include various data types and support nesting.
  • Schema Flexibility: MongoDB does not mandate a predefined schema just like the traditional databases. Each document within a collection can have a unique structure.
  • Scalability and Flexibility: MongoDB is designed for horizontal scalability enabling to add more servers to the MongoDB database for enhanced availability and performance.
  • Indexing: MongoDB offers various types of indexes to optimize query performance.
  • Smart Queries: MongoDB employs a query language resembling JSON, enabling the execution of powerful and expressive queries.
  • Cross-Platform Compatibility: MongoDB is cross-platform, supporting operating systems such as Windows, Linux and macOS

Basic Terminologies of MongoDB

  • Collections: A collection is a container for MongoDB documents. It is a grouping of documents that can be thought of a table in a relational database. Collections in MongoDB, however, do not enforce a predefined schema, allowing documents within the same collection to have different structures.
  • Documents: A document is a basic unit of data in MongoDB. It is a JSON-like object that consists of key-value pairs. Documents are stored in collections and represent the actual data entities. Each document can have a different structure, providing flexibility in data representation.
  • Field: A field is a key-value pair within a MongoDB document. The key represents the field name, and the value is the associated data. Fields can hold various types of data, including strings, numbers, arrays, and even nested documents. Fields collectively define the structure and content of a document.

Getting Started with MongoDB

Basic Database Operations

Creating Database

To create a new database you can use the use command. MongoDB will automatically create the database if it doesn't already exist.

use my_database

View Databases

showcommand will display a list of all databases currently present on the server. Keep in mind that some databases, such as “admin” and “local” are system databases used by MongoDB itself.

show dbs

View current database

To view the current database in MongoDB, you can use the db command. This command will show you the name of the current database you are working with.

db

Drop database

To drop a database, you can use the db.dropDatabase() command. However, it's important to exercise caution because dropping a database permanently deletes all data stored in that database. Make sure you are absolutely certain before executing this command.

use new_db
db.dropDatabase()

Collection Query Operations

Creating a new collection

You can create a new collection by inserting a document into it. Collections are created implicitly when you insert the first document into them. Here’s how you can create a new collection:

db.createCollection("cars")

Inserting a document

Use the insertOne method to insert a single document into a collection. For example:

db.cars.insertOne({
name: "Porsche",
model: "911 GT3",
year: 1999,
top_speed: 319
})

Use the insertMany method to insert a multiple document into a collection. For example:

db.cars.insertMany(
[
{
name: "McLaren",
model: "720s",
year: 2017,
top_speed: 341
},
{
name: "Porsche",
model: "Taycan 4S",
year: 2019,
top_speed: 260
}
]
)

View collections

Use the show collections command to list all collections within database. If there are no collections in the current database, the output will be empty. Collections are created implicitly when you insert documents into them for the first time.

show collections

View all documents

To view all documents you can use the find method in the MongoDB shell. Here's an example:

db.cars.find()

Search for a document

To search for a document you can use the find method with a query. The query specifies the criteria that the documents must meet to be included in the result set. Here's an example:

db.cars.find(
{
name:"Porsche"
}
)

Limit

The limit method is used to limit the number of documents returned by a query. This can be useful when you want to retrieve only a specific number of documents from a collection especially if the result set could be large.

db.cars.limit(2)

Count

You can use the count method to count the number of documents that match a given query.

db.cars.count()

// Count documents that meet a specific condition
db.cars.count(
year: 2019
)

Sorting the collections

You can use the sort method to sort the documents returned by a query. The sort method takes an object where you specify the fields by which you want to sort and their order (ascending [1] or descending[-1]).

db.cars.find().sort({year:-1})

Updating the collections

You can use the updateOne or updateMany method to update documents in a collection.

db.cars.updateOne({
model:"Tycan 4S"
},
{
$set : {
top_speed:320
}
}
)
// Updating collection by UpdateMany()
db.cars.updateMany(
[
{
model:"Tycan 4S"
},
{
$set : {
top_speed:320
}
},
{
model:"911 GT3"
},
{
$set : {
top_speed:260
}
}])

Delete Document

You can use the deleteOne or deleteMany method to remove documents from a collection.

db.cars.deleteOne({
name:"Porsche"
})

// Using DeleteMany()
db.cars.DeleteMany({
name:"Porsche" // Will Delete all the entries of Porsche
})

Projection

Projection is known as the process of limiting the fields that should be returned in the result set of a query. This can be useful when you only need specific fields from documents rather than the entire document. The find method in MongoDB supports projection by allowing you to pass a second argument that specifies which fields to include or exclude.

db.cars.find({}, {_id:1, name:1, top_speed:1}) // Included
db.cars.find({}, {_id:0}) // ID is excluded

Query Operators

MongoDB provides a variety of query operators that can be used to perform operations such as comparison, logical operations, and evaluation in queries. Here’s a brief overview of some commonly used operators:

Comparison Operators

Equality ($eq)

Matches values that are equal to a specified value.

{ field: { $eq: value } }
  • Inequality($ne): Matches values that are not equal to a specified value.
{ field: { $ne: value } }
  • Greater Than($gt): Matches values that are greater than a specified value.
{ field: { $gt: value } }
  • Greater Than or Equal To($gte): Matches values that are greater than or equal to a specified value.
{ field: { $gte: value } }
  • Less Than ($lt): Matches values that are less than a specified value.
{ field: { $lt: value } }
  • Less Than or Equal To ($lte): Matches values that are less than or equal to a specified value.
{ field: { $lte: value } }

Logical Operators

  • AND ($and): Joins query clauses with a logical AND.
{ $and: [ { condition1 }, { condition2 }, ... ] }
  • OR ($or): Joins query clauses with a logical OR.
{ $or: [ { condition1 }, { condition2 }, ... ] }
  • NOT ($not): Inverts the effect of a query expression and returns documents that do not match the query expression.
{ field: { $not: { $eq: value } } }

Evaluation Operators

  • Exists($exists): Matches documents that have the specified field.
{ field: { $exists: true } }
  • Where($where): Matches documents that satisfy a JavaScript expression.
{ $where: "this.field == this.otherField" }

Summary

The dynamic NoSQL database management system revolutionizing how we handle large volumes of data. Explore its document-oriented architecture, schema flexibility and powerful features like indexing and smart queries. For beginners, dive into the essentials from creating databases and collections to mastering collection query operations with hands-on guidance. Unearth the magic of MongoDB’s query operators, empowering you to perform complex operations with ease. This comprehensive guide transforms the complexities of MongoDB into an exciting adventure for those venturing into the realm of modern data management.

--

--

Muhammad Fahad
Muhammad Fahad

Written by Muhammad Fahad

Enthusiastic tech aficionado with a relentless drive to explore new trends and technologies / Data Engineer | Cloud | Data Warehouse

No responses yet