📚

MongoDB in One Hour

Jul 12, 2024

MongoDB in One Hour

Introduction to MongoDB

  • MongoDB: A NoSQL database management system.
    • Manages large amounts of data, favored by big tech companies.
    • Uses a NoSQL format to store and retrieve data.
  • NoSQL: Not only SQL. Data stored in various formats besides a traditional SQL table.
    • Instead of rows and columns, data is stored as field-value pairs within a document.
    • Document: Single row in SQL, stored in BSON (binary JSON).
    • Collection: Group of documents.
    • Database: Group of collections.

Prerequisites

  • Some experience with an object-oriented programming language (Python, Java, C++, C#, JavaScript).

Installation Process

  1. Download MongoDB
  • Go to mongodb.com -> Resources -> Server -> Installation.
    • Follow installation steps based on OS (Windows, MacOS, Linux).
  1. Install MongoDB Community Edition
  • Choose version, platform (Windows/Mac/Linux), installation package.
    • Save and run the installer.
  1. Install MongoDB Compass
  • Graphical User Interface (GUI) for managing databases.
    • Open Compass and establish a connection.
  1. Install MongoDB Shell (mongosh)
  • Download from MongoDB website -> Resources -> MongoDB Shell.
    • Extract and add to environment variables for easy access.
  1. Integration with VS Code
  • Install MongoDB extension in VS Code.
    • Run MongoDB Shell from VS Code terminal.

Creating and Using Databases

  • Show all databases: show dbs
    • Displays a list of all current databases.
  • Use a database: use <database_name>
    • Switches to the specified database or creates a new one if it doesn’t exist.
  • Create a collection: db.createCollection(<collection_name>)
  • Show collections: show collections
    • Lists all collections in the current database.
  • Drop a database: db.dropDatabase()
    • Deletes the current database.

Inserting Documents

  • Insert one document: db.<collection>.insertOne({ <field>: <value>, ... })
    • Example: db.students.insertOne({ name: "SpongeBob", age: 30, GPA: 3.2 })
  • Find documents: db.<collection>.find()
    • Returns all documents in the collection.
  • Insert many documents: db.<collection>.insertMany([{ <field>: <value>, ... }, ... ])

Data Types in MongoDB

  • String: Series of text within quotes. E.g., "Larry"
  • Integer: Whole numbers. E.g., 32
  • Double: Numbers with decimal portions. E.g., 2.8
  • Boolean: True or false.
  • Date Objects: Use new Date() for current date and time.
  • Null: No value.
  • Arrays: List multiple values. E.g., ["Biology", "Chemistry"]
  • Nested Documents: Document within a document. E.g., Address field with street, city, zip code.

Sorting and Limiting Documents

  • Sort documents: db.<collection>.find().sort({ <field>: 1 | -1 })
    • Ascending (1) or descending (-1) order.
  • Limit results: db.<collection>.find().limit(<number>)
    • Limits the number of documents returned.
  • Combining sort and limit:
    • E.g., Highest GPA: db.students.find().sort({ GPA: -1 }).limit(1)

Using the Find Method

  • Basic usage: db.<collection>.find({ <query> }, { <projection> })
    • Query parameter: Selection filters.
    • Projection parameter: Fields to return.
  • Example Queries:
    • Find by name: { name: "SpongeBob" }
    • Filter by GPA: { GPA: 4.0 }
    • Include/exclude fields: { _id: false, name: true, GPA: true }_

Updating Documents

  • Update one document: db.<collection>.updateOne({ <filter> }, { $set: { <field>: <value> } })
    • Example: db.students.updateOne({ name: "SpongeBob" }, { $set: { fullTime: true } })
  • Update many documents: db.<collection>.updateMany({ <filter> }, { $set: { <field>: <value> } })
  • Unset field: db.<collection>.updateOne({ <filter> }, { $unset: { <field>: "" } })

Deleting Documents

  • Delete one document: db.<collection>.deleteOne({ <filter> })
    • Example: db.students.deleteOne({ name: "Larry" })
  • Delete many documents: db.<collection>.deleteMany({ <filter> })
  • Example Filters:
    • By name: { name: "Larry" }
    • Field exists: { <field>: { $exists: <boolean> } }

Comparison Operators

  • Not equal: { <field>: { $ne: <value> } }
  • Less than: { <field>: { $lt: <value> } }
  • Greater than: { <field>: { $gt: <value> } }
  • Range: { <field>: { $gte: <min_value>, $lte: <max_value> } }
  • In / Not in:
    • In: { <field>: { $in: [ <value1>, <value2> ] } }
    • Not in: { <field>: { $nin: [ <value1>, <value2> ] } }

Logical Operators

  • And: { $and: [ { <expression1> }, { <expression2> } ] }
  • Or: { $or: [ { <expression1> }, { <expression2> } ] }
  • Nor: { $nor: [ { <expression1> }, { <expression2> } ] }
  • Not: { <field>: { $not: { <operator>: <value> } } }

Indexes

  • Creating an index: db.<collection>.createIndex({ <field>: 1 | -1})
    • E.g., { name: 1 } (ascending order)
  • Viewing indexes: db.<collection>.getIndexes()
  • Dropping an index: db.<collection>.dropIndex(<index_name>)

Collections

  • Creating a collection: db.createCollection(<name>, { options })
    • Options: capped, size, max, autoIndexId
  • Dropping a collection: db.<collection>.drop()

Conclusion

  • Remember to like, comment, and subscribe if you found this MongoDB tutorial helpful!