2 min read
Back to all articles

MongoDB Cheat Sheet

MongoDB Logo

MongoDB is a popular NoSQL database used in modern web applications. With its flexible document-based data model and scalability, it has become a go-to database for many developers. However, with its many features and options, it can be overwhelming to remember all the commands and syntax. That’s why a MongoDB cheat sheet can be a handy resource for developers who want to quickly reference the essential commands and operators.

  1. Installation

  2. Download MongoDB from the official website

  3. Install MongoDB on your system
  4. Start the MongoDB server using the command: mongod

2. Basic commands:

  • Show all databases: show dbs
  • Select a database: use <database>
  • Show all collections in the current database: show collections
  • Insert a document into a collection: db.<collection>.insertOne(<document>)
  • Find all documents in a collection: db.<collection>.find()
  • Find documents that match a specific condition: db.<collection>.find(<query>)
  • Update a document: db.<collection>.updateOne(<filter>, <update>)
  • Delete a document: db.<collection>.deleteOne(<filter>)
  • Delete all documents in a collection: db.<collection>.deleteMany({})

3. Query Operators:

  • Comparison Operators: $eq, $ne, $lt, $lte, $gt, $gte
  • Logical Operators: $and, $or, $not
  • Element Operators: $exists, $type
  • Array Operators: $in, $nin, $all, $size

4. Aggregation:

  • Group documents by a specific field: db.<collection>.aggregate([{ $group: { _id: <field>, <accumulator> } }])
  • Sort documents by a specific field: db.<collection>.find().sort({ <field>: 1/-1 })
  • Limit the number of documents returned: db.<collection>.find().limit(<limit>)
  • Skip a certain number of documents: db.<collection>.find().skip(<skip>)
  • Count the number of documents in a collection: db.<collection>.count()

5.Indexing:

  • Create an index: db.<collection>.createIndex({ <field>: 1/-1 })
  • Show all indexes in a collection: db.<collection>.getIndexes()
  • Remove an index: db.<collection>.dropIndex({ <field>: 1/-1 })

In conclusion, a MongoDB cheat sheet can be an incredibly useful resource for developers who work with MongoDB on a regular basis. It provides a quick reference for the essential commands and operators needed to interact with the database. By keeping this cheat sheet handy, developers can increase their productivity and reduce the time spent searching for commands and syntax. Whether you’re a beginner or an experienced MongoDB user, a cheat sheet can be a valuable tool to have in your arsenal.

Emdadul Islam

> Written by

Emdadul Islam

Software Engineer. View profile →

Read more