Most Used MongoDB commands and operations

MongoDB is a document-oriented database, which means that documents are the basic unit of data storage.

  • Documents are JSON objects, which means that they can be easily created and manipulated using JavaScript.
  • MongoDB is a schema-less database, which means that you do not need to define a schema for your data.
  • This makes MongoDB very flexible and easy to use.

Here's a MongoDB cheatsheet with some commonly used commands and operations:

Database Operations:

  • Show all databases: show dbs
  • Create or switch to a database: use
  • Drop/delete a database: db.dropDatabase()

Collection Operations:

  • Show all collections: show collections
  • Create a collection: db.createCollection("")
  • Drop/delete a collection: db..drop()

Document Operations:

  • Insert a document: db..insertOne() or db..insertMany([, , ...])
  • Find documents: db..find()
  • Update a document: db..updateOne(, ) or db..updateMany(, )
  • Delete a document: db..deleteOne() or db..deleteMany()

Query Operators:

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

Aggregation Framework:

  • Perform aggregation pipeline: db..aggregate([, , ...])
  • Common stages: $match, $group, $project, $sort, $limit, $skip, $unwind, $lookup, $addFields

Indexing:

  • Create an index: db..createIndex({ "": })
  • List all indexes: db..getIndexes()
  • Drop an index: db..dropIndex("")

Miscellaneous:

  • Count documents: db..countDocuments()
  • Show the first document: db..findOne()
  • Show the list of databases: show dbs
  • Show the current database: db

Please note that represents the name of the collection, represents the query or filter expression, and represents a JSON-like document.