Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 

Repository files navigation

MongoDB Notes

MongoDB is a NoSQL database management system that can manage a humongous amount of data.
Unlike relational database management systems, MongoDB uses a NoSQL format to store and retrieve data.

NoSQL Diagram

NoSQL stands for Not Only Structured Query Language.
It means data is stored in various formats besides a traditional SQL table.

SQL vs NoSQL

Rather than storing data in rows and columns within a table (as in SQL), MongoDB stores related data as a single document.

Think of each document as a single row in a SQL table:

Rows vs Documents

Data in each document is stored as field-value pairs, similar to JSON format (technically BSON: Binary JavaScript Object Notation).
The general idea is that data frequently accessed together is stored together, rather than in separate tables, because SQL joins can be complex.

{
   name: 'Spongebob',
   age: 30,
   gpa: 3.2,
   fullTime: false
}
{
   name: 'Patrick',
   age: 38,
   gpa: 1.5,
   fullTime: false
}
{
   name: 'Sandy',
   age: 27,
   gpa: 4,
   fullTime: true
}

MongoDB Structure

  • Document: A group of field-value pairs representing an object.
    A document

  • Collection: A group of one or more documents.
    A collection

  • Database: A group of one or more collections.
    A database

This structure makes working with and scaling your database easy.


Basic Commands to Get Started

  • Establish the connection by initiating the MongoDB shell using the mongosh command.
  • Type cls to clear the screen.
  • Type exit to exit the MongoDB shell.

Creating and Using Databases

  • show dbs — Show all databases.
  • use <database_name> — Use an existing database or create a new one.
    • Example: use school

A new database will not appear in the list until you add a collection to it.

Creating a Collection

Use the createCollection method:

db.createCollection("students")

To drop the current database:

db.dropDatabase()

Create a collection and drop a database


Inserting Documents

Switch to the database you want to use:

use school

Insert One Document

db.students.insertOne({name: "Spongebob", age: 30, gpa: 3.2})

Insert Multiple Documents

db.students.insertMany([
  {name: "Spongebob", age: 30, gpa: 3.2},
  {name: "Patrick", age: 38, gpa: 1.5},
  {name: "Sandy", age: 27, gpa: 4}
])

InsertMany method


Basic Data Types in MongoDB

  1. String: Series of text within quotes (e.g., "Monkey D Luffy")
  2. Integer: Whole numbers (e.g., 27)
  3. Double: Numbers with decimal portions (e.g., 3.2)
  4. Boolean: true or false
  5. Date Objects: Use new Date() or pass a date string.
  6. Null: Represents no value.
  7. Arrays: A field that can have more than one value.
  8. Nested Documents: Useful for addresses or embedded objects.

MongoDB Data Types


Sorting and Limiting Documents

To sort documents, use method chaining with find() and sort():

db.students.find().sort({name: 1})   // Sort by name in ascending (A-Z) order
db.students.find().sort({name: -1})  // Sort by name in descending (Z-A) order
db.students.find().sort({gpa: 1})    // Sort by GPA ascending
db.students.find().sort({gpa: -1})   // Sort by GPA descending

Sort Name Field In Alphabetical Order
Sort Name Field In Reverse Alaphabetical Order

Limiting Results

Use the limit() method to restrict the number of documents returned:

db.students.find().limit(1)

Limit One Document

You can combine sort() and limit():

db.students.find().sort({gpa: -1}).limit(1) // Student with the highest GPA

Student With The Highest GPA


Querying Documents

The find() method returns all documents by default.
To filter results, use query and projection parameters:

db.students.find({query}, {projection})

Query Parameter

  • Filters documents based on criteria.

Examples:

db.students.find({name: "Zoro"})
db.students.find({gpa: 2.5})
db.students.find({gpa: 3.8, fullTime: false})

Find Method With Query Parameter
Find Method With Two Filters

Projection Parameter

  • Specifies which fields to return.

Examples:

db.students.find({}, {name: true}) // Only return names
db.students.find({}, {_id: false, name: true}) // Exclude _id, only names
db.students.find({}, {_id: false, name: true, gpa: true}) // Only names and GPA

Find Method Projection Parameter


Updating Documents

You can update one or many documents.

updateOne Method

  • Takes two parameters: filter and update.
db.students.updateOne({filter}, {update})

Example: Add or Update a Field

db.students.updateOne(
  {name: "Sanji"},
  {$set: {fullTime: true}}
)

Update One Method

Example: Update Using ObjectId

It's safer to update using the unique ObjectId, especially if names are not unique.

db.students.updateOne(
  {_id: ObjectId("...")},
  {$set: {fullTime: false}}
)

Update One Method_

Example: Remove a Field

Use the $unset operator to remove a field:

db.students.updateOne(
  {name: "Sanji"},
  {$unset: {fullTime: ""}}
)

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors