TechWriterDev
  • Cloud
    • AWS
      • 00_Doubts
      • CloudPractitioner
        • Cloud Computing
        • AWS Global Infrastructure
        • Introduction to AWS EC2
        • Elastic load balancer(ELB)
        • 04_Messaging_Queuing
        • Aditional Computing Service
        • Accessing AWS resources
        • AWS Networking
        • Storage
        • Amazon Database Solutions
        • Monitoring Tools
        • AWS Security
        • Distributed Denial Of Service Attacks
      • DeveloperAssociate
        • References
        • AWS DVA-C02 Services Index
        • Services
          • 00_IAM
            • Identity and Access Management (IAM)
            • Account Protection Mechanisms
            • Access Mechanism of AWS Resources
            • Security Tools
            • Responsibility Model
            • Advanced Concepts
          • 01_EC2
            • Elastic Compute Cloud (EC2)
            • EC2 Volume Types
            • Amazon Machine Image (AMI)
            • AWS charges for IPv4 address
          • 02_SecurityGroups
            • Security Groups
          • 03_Elastic_LoadBalancing
            • Terminology
            • Elastic load balancer
            • Features
            • Basics
          • 04_AutoScaling
            • Auto Scaling
          • 05_RDS
            • Relational Database Service (RDS)
            • Aurora
            • Security
            • RDS Proxy
          • 06_ElastiCache
            • Cache
            • Cache Offerings
          • 07_Route53
            • Basics of DNS
            • Route 53
          • 08_VPC
            • Virtual Private Cloud (VPC)
          • 09_S3
            • Simple Storage Service (S3)
            • S3 Features
            • S3 Encryption
            • S3 Features
            • S3 Bucket Policy and IAM Policy
          • 10_ECS
            • Elastic Container Service (ECS)
            • Elastic Container Registry (ECR)
            • AWS Copilot
          • 11_EKS
            • Elastic Kubernetes Service (EKS)
          • 12_SDK_CLI_Tips
            • Access AWS Resources
          • 13_CloudFront
            • Cloud Front
          • 14_Messaging
            • Simple Queue Service (SQS)
            • Simple Notification Service (SNS)
            • Fan Out Pattern
            • Kinesis
            • Compare and Contrast
          • 15_ElasticBeanStalk
            • Elastic Beanstalk
          • 16_CloudFormation
            • CloudFormation
            • Dynamic References
          • 17_Monitoring
            • AWS Monitoring
            • AWS CloudWatch
            • CloudWatch Alarms
            • Synthetics Canary
            • Amazon EventBridge (formerly CloudWatch Events)
            • X-Ray
            • OpenTelemetry
            • CloudTrail
          • 18_Lambda
            • Lambda
            • Lambda Integrations
            • Configuring Lambda
            • Lambda Layers
          • 19_API_Gateway
            • API Gateway
            • API Gateway Integrations
          • 20_DynamoDB
            • DynamoDB
            • Operations
            • Indexes
            • DynamoDB Accelerator (DAX)
            • DynamoDB Streams
            • Transactions
            • Integrations
          • 21_CICD
            • CICD
            • CodeCommit
            • CodePipeline
            • CodeBuild
            • CodeDeploy
            • CodeArtifact
            • CloudGuru
          • 22_SAM
            • Serverless Application Model (SAM)
          • 23_CDK
            • Cloud Development Kit (CDK)
          • 24_StepFunctions
            • Step Functions
            • Types of step function
          • 25_AppSync
            • AppSync
          • 26_Amplify
            • Amplify
          • 27_STS
            • Security Token Service (STS)
          • 28_DirectoryService
            • Active Directory
          • 29_KMS
            • Encryption
            • KMS API
            • Features
            • Cloud Hardware Security Module (HSM)
          • 30_SSM_Store
            • SSM Parameter Store
          • 31_SecretsManager
            • Secrets Manager
          • 32_Cognito
            • Cognito
      • Questions
        • AWS_Region
        • EC2
        • IAM
  • Database
    • MongoDb
      • Mongo db Basics
      • Mongo DB Atlas
      • Document
      • Import-Export based on Data Format
      • Mongo Shell Commands
      • Query Operators
      • Indexes
      • Upsert
      • MongoDB Aggregation Framework
      • Aggregation Framework Operators
    • PostgreSQL
      • POSTGRE SQL DataTypes
      • About table
      • Constraints
  • Technologies
    • RabbitMQ
      • RabbitMQ Concepts
      • Introduction to Exchanges
      • Introduction to Queues
    • Terraform
      • 00_Introduction
      • Configuration blocks
      • Commands
      • Variables
      • Terraform Cloud
      • Modules
  • Languages
    • Java
      • Logging
        • Getting Started
      • 00_Core
        • 00_Basics
          • Java Vs C++
          • Object oriented principles
          • Steps to compile a java program
          • JVM Internals
          • Understanding Java Development Kit
          • What is JIT Compiler?
          • Java data types
          • 07_identifiers_type_conversion
          • 08_references_and_packages
          • Steps for attaching scanner
        • Concurrency
          • 00_Threads
            • Threads
          • 01_ExecutorFramework
            • Executor Framework
            • Asynchronous Computation
      • 01_Backend
        • 01_HttpAndWebServerBasics
          • HTTP
          • Content Type
          • Web Server
        • 02_J2EE_Basics
          • J2EE_Basics
          • Why HttpServlet classs is declared as abstract class BUT with 100 % concrete functionality ?
        • 03_TomCatAndSession
          • What is a Session?
          • WebContainer
        • 04_PageNavigation
          • Cookies Additional Information
          • Page Navigation Techniques
        • 05_AboutServlet
          • CGI v/s Servlet
          • Executor Framework
          • Servlet Life cycle
          • SERVLET CONFIG
          • Servlet Context
          • Servlet Listener (web application listener)
        • 08_SpringBoot
          • Spring Boot
          • Some common annotations used in spring eco system
        • 09_SpringDataJPA
          • Spring Data JPA
        • Java_Language_Changes
          • JDK enhancement tracking reference
        • 06_ORM_Hibernate
          • readmes
            • Hibernate
            • Advantages of Hibernate
            • Hibernate Caching
            • Hibernate API
            • Hibernate Query API
            • Hibernate Annotations and JPQL
            • Entity and Value Type
        • 07_SpringFramework
          • bean_validation
            • Bean Validation
          • core
            • readme
              • Spring
              • Spring Framework Modules
              • Spring MVC Request flow
              • Dependency Injection
              • Spring Beans
              • 06_Spring_Framework_Annotations
      • 03_Tools
        • Maven
          • Maven
  • SoftwareEngineering
    • DesignPatterns
      • Notes
        • Basics
        • OOP
        • SOLID Principles
        • 03_Creational
          • Abstract Factory (aka Kit)
          • Builder
          • Factory Method (aka Virtual constructor)
          • Prototype
          • Singleton
        • 04_Structural
          • Adapter (aka Wrapper)
          • Bridge (aka Handle | Body)
          • Composite
          • Decorator (aka Wrapper)
          • Facade
          • Flyweight
          • Proxy (aka Surrogate)
        • 05_Behavioral
          • Chain of Responsibility
          • Command (aka Action | Transaction)
          • Iterator (aka Cursor)
          • Observer (aka Publish-Subscribe | Dependents)
          • Strategy (aka Policy)
    • Principles
      • REST
        • REST
  • Tools
    • Containers
      • Docker
        • Docker
        • Docker Image
        • Commands
        • Compose
        • Best Practices
      • Kubernetes
        • Kubernetes
    • VCS
      • Git
        • Quick reference of useful Git commands
Powered by GitBook
On this page
  1. Database
  2. MongoDb

Mongo Shell Commands

PreviousImport-Export based on Data FormatNextQuery Operators

Last updated 4 months ago

  • Mongo shell is a fully functioning JavaScript interpreter, which means that you can create things like JavaScript functions and variables in it.

  • Once mongo shell is installed, we can use the following commands when we dont have a GUI to interact with mongodb.

Common commands

  1. Show databases

show dbs

  1. Select database.

use <database_name> //no angular brackets

  • The above command can be used to view the available namespaces.

  1. To view collections in the database once a database is selected using above command.

show collections

  1. Admin database consists of all the information about users.

  2. Find Command - To query the collections.

    • Returns a cursor, basically a pointer to the query result.

      • To find all documents in a collection

        db.<collection_name>.find({}) OR db.<collection_name>.find()

        • The above command returns at max 20 entries. We can request more by (typing it).

      • To find documents based on criteria

        db.<collection_name>.find({"key": value}) db.<collection_name>.find({"key": value, "key":value })

      • To count the documents in the returned collection

        db.<collection_name>.find({"key":value }).count()

      • To pretty print the result of find query

        db.<collection_name>.find({"key":value }).pretty()

      • To find one document, this one document can be any random document in the collection.

        db.<collection_name>.findOne()

    • Projections in find query

      db.<collection_name>.find({<query>}, {<projections>})

      • Example

         db.account.find(
               { "name": "Joe" },
               { "age": 1, "address": 0, "_id": 0 }
            )
      • In the above example, age is projected and address is not projected in the result.

        • 1 -> include the field

        • 0 -> exclude the field

      • Use only 1s or 0s donot mix and match, exception being _id field which is always projected, if not explicitly mentioned to be excluded.

  3. Insert Command - To insert document/s in to a collection

    • To insert one document

      db.<collection_name>.insert()

      • Example

         db.accounts.insert({
               "_id":ObjectId("61d982f17d3abc1d237445b3"),
               "name" : "John Doe",
               "age":25
         })
      - In the above example "_id" field is specified which needs to be unique in the accounts collection, if not specified mongodb will automatically generate one.
    • To insert many documents at once

      db.<collection_name>.insert([<document1>, <document2> ...])

      • Example

         db.accounts.insert([
         {
               "_id":ObjectId("61d982f17d3abc1d237445b3"),
               "name" : "John Doe",
               "age":25
         },
         {
               "_id":ObjectId("61d982f17d3abc1d237445b4"),
               "name" : "Kirsten Smith",
               "age":26
         } 
         ])
      • When inserting duplicate documents, insertion fails on occurence of first duplicate document, hence preventing insertion of remaining valid (non-duplicating) entries. This can be prevented by using "ordered" flag as follows,

          db.accounts.insert([
         {
               "_id":ObjectId("61d982f17d3abc1d237445b3"),
               "name" : "John Doe",
               "age":25
         },
         {
               "_id":ObjectId("61d982f17d3abc1d237445b4"),
               "name" : "Kirsten Smith",
               "age":26
         } ], 
         **{ 
            "ordered":false
         }**
         )
      • Setting ordered flag as false makes documents insertion into collection in unordered manner. This helps when inserting duplicate documents with same "_id" value, so that failure will occur only for duplicate documents and insertion for non duplicate documents will be successful.

  4. Update Command - To update document/s in a collection

    • To update one document.

    db.<collection_name>.update({<restriction>}, {<update operation>})

    • Example

    db.accounts.update(
       {
          "name": "Joe"
       },
       {
          "$set":{
             "name": "Jason"
          }
       }
    )
    • To update many document.

    db.<collection_name>.updateMany({<restriction>}, {<update operation>})

    • Example

    db.accounts.updateMany(
       {
          "age": 17
       },
       {
          "$inc":{
             "age": 1
          }
       }
    )
    • The above update operators i.e., $set and $inc can take more than one fields to update.

    • To add an element to an existing array in document use $push opeerator.

    • Read more about .

  5. Delete Command - To delete document/s from a collection

    • To delete one document

    db.<collection_name>.deleteOne({<restriction>})

    • Example

      db.accounts.deleteOne({"name": "Joe"})
    • To delete many document

    db.<collection_name>.deleteMany({<restriction>})

    • Example

       db.accounts.deleteMany({"name": "Joe"})
  6. Drop Collection

    db.<collection_name>.drop()

  7. db

  • This command prints the current db selected.

update operators