DEV Community

Syed Muhammad Ali Raza
Syed Muhammad Ali Raza

Posted on

Basic MongoDB Commands

A Comprehensive Guide

introduction:

MongoDB, a popular NoSQL database, offers a flexible and scalable solution for data storage and management. As a developer or database administrator working with MongoDB, familiarity with the command line interface and the commands it provides is essential. In this article, we will explore a set of MongoDB commands that will allow you to perform several operations efficiently.

Database operations:

  • Show all databases: show dbs
  • Switch to a specific database: Use
  • Create a new database using:
  • Drop a database: db.dropDatabase()

Image description

Collection procedure:

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

Document Process:

  • Insert document in collection: db .insertOne () or db.
  • Find documents from a collection: db .find ()
  • Update document: db .updateOne (, ) or db.
  • Delete document: db .deleteOne () or db.
  • Questions and filters:
  • Key query: db .find()
  • Query with criteria: db .find ()
  • Query with projection (return specific fields): db .find (, )
  • Sort result: db. .find()
  • Limit the number of results: db .find(). Limit ()

Indexing:

  • Create index: db.createIndex(, )
  • List all indexes: db.getIndexes()
  • Drop index: db .dropIndex ()
  • Aggregation:
  • Run the collection pipeline: db .aggregate ()
  • Group document: $ group stage
  • Filter docs: $ match phase
  • Sort documents: $phase sort
  • Project field: $ project stage
  • Perform arithmetic operations: phase $addFields

User and security management:

  • Create user: db.createUser()
  • Change user role: db.updateUser (, )
  • Drop User: db.dropUser ()
  • Enable authentication: Update the MongoDB configuration file and restart the server.

The results:

MongoDB commands are the basis for efficient management and interaction with MongoDB databases. This comprehensive guide provides an overview of essential commands for running databases, collections, documents, queries, indexing, aggregation, and user management operations. By mastering these commands, you will be equipped to work efficiently with MongoDB and take advantage of its capabilities to build scalable and reliable applications.

Top comments (1)

Collapse
 
friedrickdev profile image
FriedRickaDev

Provide Some Basic code