DEV Community

Abdul Haseeb
Abdul Haseeb

Posted on

MongoDB Cheat Sheet

1. MongoDB Basics

  • MongoDB is a NoSQL, document-oriented database that stores data in flexible, JSON-like documents.

2. MongoDB Shell Commands

  • Start MongoDB shell:
  mongosh
Enter fullscreen mode Exit fullscreen mode
  • Show Databases:
  show dbs
Enter fullscreen mode Exit fullscreen mode
  • Switch/Create Database:
  use database_name
Enter fullscreen mode Exit fullscreen mode
  • Show Collections (tables equivalent):
  show collections
Enter fullscreen mode Exit fullscreen mode

3. Create a Collection

  • Create Collection:
  db.createCollection("collection_name")
Enter fullscreen mode Exit fullscreen mode

Collections are created automatically when you insert a document.

4. CRUD Operations

Insert Documents

  • Insert One Document:
  db.collection_name.insertOne({key: "value", key2: "value2"})
Enter fullscreen mode Exit fullscreen mode
  • Insert Multiple Documents:
  db.collection_name.insertMany([
      {key: "value", key2: "value2"},
      {key: "value3", key2: "value4"}
  ])
Enter fullscreen mode Exit fullscreen mode

Find Documents

  • Find All Documents:
  db.collection_name.find()
Enter fullscreen mode Exit fullscreen mode
  • Find with Condition:
  db.collection_name.find({key: "value"})
Enter fullscreen mode Exit fullscreen mode
  • Pretty Print:
  db.collection_name.find().pretty()
Enter fullscreen mode Exit fullscreen mode

Update Documents

  • Update One Document:
  db.collection_name.updateOne({key: "value"}, {$set: {key2: "new_value"}})
Enter fullscreen mode Exit fullscreen mode
  • Update Multiple Documents:
  db.collection_name.updateMany({key: "value"}, {$set: {key2: "new_value"}})
Enter fullscreen mode Exit fullscreen mode

Delete Documents

  • Delete One Document:
  db.collection_name.deleteOne({key: "value"})
Enter fullscreen mode Exit fullscreen mode
  • Delete Multiple Documents:
  db.collection_name.deleteMany({key: "value"})
Enter fullscreen mode Exit fullscreen mode

5. Querying Data

Operators in Queries

  • Equality:
  db.collection_name.find({key: "value"})
Enter fullscreen mode Exit fullscreen mode
  • Greater Than (GT):
  db.collection_name.find({key: {$gt: value}})
Enter fullscreen mode Exit fullscreen mode
  • Less Than (LT):
  db.collection_name.find({key: {$lt: value}})
Enter fullscreen mode Exit fullscreen mode
  • In:
  db.collection_name.find({key: {$in: [value1, value2]}})
Enter fullscreen mode Exit fullscreen mode

AND/OR Conditions

  • AND Condition (default behavior):
  db.collection_name.find({key1: "value1", key2: "value2"})
Enter fullscreen mode Exit fullscreen mode
  • OR Condition:
  db.collection_name.find({$or: [{key1: "value1"}, {key2: "value2"}]})
Enter fullscreen mode Exit fullscreen mode

6. Sorting, Limiting, and Pagination

  • Sort Results:
  db.collection_name.find().sort({key: 1})   // Ascending
  db.collection_name.find().sort({key: -1})  // Descending
Enter fullscreen mode Exit fullscreen mode
  • Limit Results:
  db.collection_name.find().limit(5)
Enter fullscreen mode Exit fullscreen mode
  • Skip Results (pagination):
  db.collection_name.find().skip(5).limit(5)
Enter fullscreen mode Exit fullscreen mode

7. Indexes

  • Create Index:
  db.collection_name.createIndex({key: 1})
Enter fullscreen mode Exit fullscreen mode

1 for ascending, -1 for descending.

  • Show Indexes:
  db.collection_name.getIndexes()
Enter fullscreen mode Exit fullscreen mode

8. Aggregation

  • Basic Aggregation:
  db.collection_name.aggregate([
      {$match: {key: "value"}},
      {$group: {_id: "$key2", total: {$sum: "$key3"}}}
  ])
Enter fullscreen mode Exit fullscreen mode

9. Relationships (Embedding vs. Referencing)

  • Embedding Documents (Store related data in the same document):
  {
    _id: 1,
    name: "John",
    address: {
      street: "123 St",
      city: "New York"
    }
  }
Enter fullscreen mode Exit fullscreen mode
  • Referencing Documents (Store references to related data):
  {
    _id: 1,
    name: "John",
    address_id: ObjectId("507f191e810c19729de860ea")
  }
Enter fullscreen mode Exit fullscreen mode

10. MongoDB Atlas

  • MongoDB Atlas is a cloud database service for MongoDB.

Connecting to MongoDB Atlas

  • Connection String (from MongoDB Atlas):
  mongodb+srv://<username>:<password>@cluster0.mongodb.net/test
Enter fullscreen mode Exit fullscreen mode

11. Backup and Restore

  • Backup Database:
  mongodump --db database_name
Enter fullscreen mode Exit fullscreen mode
  • Restore Database:
  mongorestore --db database_name dump/database_name/
Enter fullscreen mode Exit fullscreen mode

12. MongoDB Operators

  • $set: Updates the value of a field.
  • $inc: Increments the value of a field.
  • $push: Appends a value to an array.
  • $pull: Removes a value from an array.
  • $exists: Checks for the existence of a field.

13. Other Useful Commands

  • Count Documents:
  db.collection_name.countDocuments()
Enter fullscreen mode Exit fullscreen mode
  • Drop Collection:
  db.collection_name.drop()
Enter fullscreen mode Exit fullscreen mode
  • Drop Database:
  db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

14. Data Types

  • Common MongoDB Data Types:
    • String
    • Number (32-bit or 64-bit integer)
    • Boolean
    • Array
    • Object
    • ObjectId
    • ISODate (for date/time)

15. Transactions (MongoDB 4.0+)

  • Start Transaction:
  session = db.getMongo().startSession();
  session.startTransaction();
Enter fullscreen mode Exit fullscreen mode
  • Commit Transaction:
  session.commitTransaction();
Enter fullscreen mode Exit fullscreen mode
  • Abort Transaction:
  session.abortTransaction();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)