MongoDB Cheat Sheet

This MongoDB cheat sheet in Markdown format that covers essential commands and concepts for working with MongoDB, including basic operations, query techniques, aggregation framework, indexing, and database management.

Basic Operations

  • Start MongoDB Server
    mongod
    
  • Connect to MongoDB
    mongo
    

Database Operations

  • Show Databases
    show dbs
    
  • Create or Switch Database
    use db_name
    
  • Drop Database
    db.dropDatabase()
    

Collection Operations

  • Show Collections
    show collections
    
  • Create Collection
    db.createCollection('collection_name')
    
  • Drop Collection
    db.collection_name.drop()
    

Document Operations

  • Insert Document
    db.collection_name.insert({key: 'value'})
    
  • Insert Multiple Documents
    db.collection_name.insertMany([{key1: 'value1'}, {key2: 'value2'}])
    
  • Find Documents
    db.collection_name.find({key: 'value'})
    
  • Find One Document
    db.collection_name.findOne({key: 'value'})
    
  • Update Document
    db.collection_name.update({key: 'value'}, {$set: {key_updated: 'new_value'}})
    
  • Delete Document
    db.collection_name.remove({key: 'value'})
    

Querying

  • Equality
    db.collection_name.find({key: 'value'})
    
  • Less Than / Greater Than
    db.collection_name.find({key: {$lt: value}}, {key: {$gt: value}})
    
  • Logical AND
    db.collection_name.find({$and: [{key1: 'value1'}, {key2: 'value2'}]})
    
  • Logical OR
    db.collection_name.find({$or: [{key1: 'value1'}, {key2: 'value2'}]})
    

Aggregation

  • Group By
    db.collection_name.aggregate([{ $group: {_id: "$key", total: { $sum: 1}}}])
    
  • Match
    db.collection_name.aggregate([{ $match: {key: 'value'}}])
    
  • Project
    db.collection_name.aggregate([{ $project: {key1: 1, key2: 1}}])
    

Indexing

  • Create Index
    db.collection_name.createIndex({key: 1})
    
  • List Indexes
    db.collection_name.getIndexes()
    
  • Drop Index
    db.collection_name.dropIndex('index_name')
    

Subscribe to dadonk

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe