Bytes
Data Science

MongoDB Cheat Sheet (Basics to Advanced)

Last Updated: 3rd August, 2024
icon

Arunav Goswami

Data Science Consultant at almaBetter

Discover the essential MongoDB commands and queries with our MongoDB cheat sheet. Learn basic commands, query syntax, aggregation operations, and more

MongoDB, a popular NoSQL database, offers high performance, high availability, and easy scalability. This cheat sheet provides a comprehensive guide to MongoDB commands, queries, and operators, making it a valuable resource for both beginners and advanced users.

Introduction to MongoDB

MongoDB stores data in flexible, JSON-like documents, making it easy to work with different data structures. Understanding the basic commands and queries is essential for efficient database management. This MongoDB cheat sheet covers various commands, query syntax, data aggregation operations, and more.

MongoDB Commands Cheat Sheet

Basic Commands

  1. Start MongoDB Shell
    • Command: mongo
    • Description: Launch the MongoDB shell to interact with the database.
  2. Connecting to MongoDB
  3. Show Databases
    • Command: show dbs
    • Description: List all databases on the server.
  4. Use a Database
    • Command: use [database_name]
    • Description: Switch to a specific database.
    • Example: use myDatabase
  5. Show Collections
    • Command: show collections
    • Description: List all collections in the current database.
  6. Create a Collection
    • Command: db.createCollection("[collection_name]")
    • Description: Create a new collection.
    • Example: db.createCollection("myCollection")
  7. Drop a Collection
    • Command: db.[collection_name].drop()
    • Description: Remove a collection from the database.
    • Example: db.myCollection.drop()
  8. Drop a Database
    • Command: db.dropDatabase()
    • Description: Drop the current database.

Data Insertion Commands

  1. Insert One Document
    • Command: db.[collection_name].insertOne({document})
    • Description: Insert a single document into a collection.
    • Example: db.users.insertOne({name: "John", age: 30})
  2. Insert Multiple Documents
    • Command: db.[collection_name].insertMany([{document1}, {document2}])
    • Description: Insert multiple documents into a collection.
    • Example: db.users.insertMany([{name: "Alice", age: 25}, {name: "Bob", age: 28}])

MongoDB Query Cheat Sheet

Basic Queries

  1. Find One Document
    • Command: db.[collection_name].findOne({query})
    • Description: Retrieve a single document that matches the query.
    • Example: db.users.findOne({name: "John"})
  2. Find Multiple Documents
    • Command: db.[collection_name].find({query})
    • Description: Retrieve all documents that match the query.
    • Example: db.users.find({age: {$gt: 25}})

Query Operators

  1. Equality
    • Command: {field: value}
    • Example: db.users.find({name: "Alice"})
  2. Greater Than
    • Command: {field: {$gt: value}}
    • Example: db.users.find({age: {$gt: 25}})
  3. Less Than
    • Command: {field: {$lt: value}}
    • Example: db.users.find({age: {$lt: 30}})
  4. Not Equal
    • Command: {field: {$ne: value}}
    • Example: db.users.find({name: {$ne: "Bob"}})
  5. Logical AND
    • Command: {$and: [{query1}, {query2}]}
    • Example: db.users.find({$and: [{age: {$gt: 25}}, {age: {$lt: 30}}]})
  6. Logical OR
    • Command: {$or: [{query1}, {query2}]}
    • Example: db.users.find({$or: [{age: 25}, {age: 30}]})

MongoDB Aggregation Cheat Sheet

Aggregation operations process data records and return computed results. These operations group values from multiple documents together and can perform various operations on the grouped data to return a single result.

Basic Aggregation Commands

  1. Match
    • Command: {$match: {criteria}}
    • Example: db.orders.aggregate([{$match: {status: "A"}}])
  2. Group
    • Command: {$group: {_id: "$field", total: {$sum: "$quantity"}}}
    • Example: db.orders.aggregate([{$group: {_id: "$item", totalQuantity: {$sum: "$quantity"}}}])
  3. Sort
    • Command: {$sort: {field: 1}}
    • Example: db.orders.aggregate([{$sort: {total: -1}}])
  4. Project
    • Command: {$project: {field1: 1, field2: 1}}
    • Example: db.orders.aggregate([{$project: {item: 1, total: 1}}])

MongoDB Shell Commands Cheat Sheet

  1. List Databases
    • Command: show dbs
    • Example: show dbs
  2. List Collections
    • Command: show collections
    • Example: show collections
  3. Switch Database
    • Command: use [database_name]
    • Example: use myDatabase
  4. Create Collection
    • Command: db.createCollection("[collection_name]")
    • Example: db.createCollection("newCollection")

MongoDB Compass Query Cheat Sheet

MongoDB Compass provides a graphical interface to manage MongoDB databases. Here's how to perform some basic queries:

  1. Find All Documents
    • Use the "Find" tab to enter an empty query {}.
  2. Filter Documents
    • Use the query bar to enter queries such as {age: {$gt: 25}}.
  3. Aggregation Pipeline
    • Use the "Aggregation" tab to build aggregation pipelines visually.

MongoDB Syntax Cheat Sheet

CRUD Operations

Create

  • db.[collection].insertOne({document}): Inserts a single document into a collection.
  • db.[collection].insertMany([{document1}, {document2}, ...]): Inserts multiple documents into a collection.

Read

  • db.[collection].find({query}): Finds all documents that match the query. Returns all documents if the query is empty.
  • db.[collection].findOne({query}): Finds a single document that matches the query.
  • db.[collection].find({query}).limit(number): Limits the number of documents returned.

Update

  • db.[collection].updateOne({filter}, {update}, {options}): Updates a single document that matches the filter.
  • db.[collection].updateMany({filter}, {update}, {options}): Updates multiple documents that match the filter.
  • db.[collection].replaceOne({filter}, {replacement}, {options}): Replaces a single document that matches the filter with a new document.

Delete

  • db.[collection].deleteOne({filter}): Deletes a single document that matches the filter.
  • db.[collection].deleteMany({filter}): Deletes multiple documents that match the filter.

MongoDB Operators Cheat Sheet

Comparison Operators

  1. $eq: Matches values that are equal to a specified value.
    • Example: {age: {$eq: 25}}
  2. $gt: Matches values that are greater than a specified value.
    • Example: {age: {$gt: 25}}
  3. $lt: Matches values that are less than a specified value.
    • Example: {age: {$lt: 30}}

Logical Operators

  1. $and: Joins query clauses with a logical AND.
    • Example: {$and: [{status: "A"}, {qty: {$lt: 30}}]}
  2. $or: Joins query clauses with a logical OR.
    • Example: {$or: [{status: "A"}, {qty: {$lt: 30}}]}
  3. $not: Inverts the effect of a query expression.
    • Example: {price: {$not: {$gt: 1.99}}}

Advanced MongoDB Queries Cheat Sheet

Indexing

  • db.[collection].createIndex({field: 1}): Creates an ascending index on the specified field.
  • db.[collection].createIndex({field: -1}): Creates a descending index on the specified field.
  • db.[collection].getIndexes(): Lists all indexes on the collection.
  • db.[collection].dropIndex("indexName"): Drops the specified index.

User Management

  • db.createUser({user: "username", pwd: "password", roles: ["role1", "role2"]}): Creates a new user with specified roles.
  • db.updateUser("username", {pwd: "newpassword"}): Updates the password for an existing user.
  • db.dropUser("username"): Deletes a user.

Backup and Restore

  • mongodump --db [database] --out [directory]: Creates a backup of the specified database.
  • mongorestore --db [database] [directory]: Restores the specified database from a backup.

Conclusion

This MongoDB cheat sheet serves as a quick reference guide for developers and database administrators. It covers essential commands, query syntax, aggregation operations, and more to help you manage and interact with your MongoDB databases efficiently. Keep this cheat sheet handy to streamline your workflow and enhance your productivity with MongoDB.

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter