Getting Started With MongoDB Shell & Basic Commands

3 min read

  • Languages, frameworks, tools, and trends

The MongoDB local shell offers the capability to establish connections to both local and remote MongoDB servers. Once connected, you gain the ability to execute commands and scripts to effectively interact with the databases and collections residing within the MongoDB server.

The MongoDB local shell serves as an invaluable tool for developers and administrators involved in MongoDB operations. It enables the execution of JavaScript-based commands and offers a wide range of functionalities for managing databases, collections, documents, indexes, and other operations. With the local shell, you can seamlessly execute queries, update documents, perform data aggregation, create indexes, and handle administrative tasks efficiently.

MongoDB utilizes the BSON format for storing data, which is particularly advantageous and easily accessible within the realm of JavaScript

Let's start with some basic commands to access the database from the terminal.

MongoDB shell commands

Below are a few MongoDB shell commands that you can begin familiarizing yourself with.

  • Install Mongosh on Mac using the command line.
brew install mongosh
Bash

Your default local port for Mongod will be 27017

  • To change the default port you can use the following command,
mongosh --port 28015
Bash
  • To check the local Database list, use the command below.

type db in terminal

  • Finally, to select the database from the list, use the following command,

type use "<database name>" in terminal

MongoDB CRUD operation commands

Moving on we can perform some basic operations on MongoDB shell.

Create

  • Insert one

To insert a single document, type the following command in MongoDB shell command terminal.

db.users.insertOne(
 {
   fullName: "The Favourite",
   email: [ "Drama", "History" ],
   subscription: 1
   isBlocked: false,
 }
)
JavaScript
  • Insert many

To insert many documents at a single go, type the following command in MongoDB shell command terminal.

db.subscriptios.insertMany([
  {
   title: Basic,
   price: free,
   expire: 0,
   details: “”
  {
   title: glory,
   price: 10$,
   expire: 0,
   details: “”
  {
   title: premium,
   price: 50$,
   expire: 0,
   details: “”
  },
])
JavaScript

Update

  • Update one

To update a single document, type the following command in MongoDB shell command terminal.

db.users.updateOne( { _id: "" },
{
 $set: {
   fullName: "Faraz Ahmed”
 }
})
JavaScript
  • Update many

To update many documents in a single go, type the following command in the MongoDB shell command terminal.

db.movies.updateMany(
 { price: { $lt: 50 } },
 {
   $set: { access: free, access_expire: 30 }
 }
)
JavaScript

Delete

  • Delete one

To delete document, type the following command in MongoDB shell command terminal.

db.movies.deleteOne( { _id: "" } )
JavaScript
  • Delete many

To delete documents many documents in a single go, type the following command in the MongoDB shell command terminal.

db.movies.deleteMany( { createdAt: { $ls: ""} } )
JavaScript

Get / Get all

  • Find all

To find all the documents from the collection, type the following command in the MongoDB shell command terminal.

db.movies.find()
Plaintext
  • Find selective

To get selective documents from the collection, type the following command in the MongoDB shell command terminal.

db.movies.find( { "genre": "Action" } )
Plaintext
  • Switch to another database

If you want to switch to another database temporarily, you can do it by running the following MongoDB shell commands.

db.getSiblingDB(<database name>).getCollectionNames();
JavaScript

Use of different conditional operators for queries like “and/or”

Example

db.movies.find( { genre: "Action", "rating": { $gte: 7 } } )

db.movies.find({
    year: 2010,
    $or: [ { "rating.wins": { $gte: 5 } }, { genres: "Drama" } ]
})
SQL

You can build a pipeline of queries/filtering to get specific data from the collection.

Example

db.orders.aggregate( [


  // Stage 1: Filter pizza order documents by pizza size
  {
     $match: { size: "medium" }
  },
  // Stage 2: Group remaining documents by pizza name and calculate total quantity
  {
     $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } }
  }

] )
Plaintext

On the first stage of the pipeline we will be filtering the data with a matching keyword where size is “medium”, then on the second stage we are grouping the filtered data with a “group” keyword.

Indexes

MongoDB utilizes indexes, which are data structures, designed to enhance query performance by facilitating efficient data retrieval from collections. Indexes store a condensed version of selected fields or values from the data, enabling the database to swiftly locate the desired documents. This optimization process significantly improves the efficiency of querying operations.

to create a ascending index

db.records.createIndex( { score: 1 } )
JavaScript

to create a descending index

db.records.createIndex( { score: -1 } )
JavaScript

We can create multi keys indexes, text indexes, wildcard indexes and much more.

Lookups

Just like the join function in other databases like MySQL, you can also perform the join functionality in MongoDB.

Syntax

To join between collections we can use “lookup”.

{$lookup:
     {
        from: <joined collection>,
        let: { <var_1>: <expression>, …, <var_n>: <expression> },
        pipeline: [ <pipeline to run on joined collection> ],
        as: <output array field>
     }
}
Plaintext

Sample post table

{
    "title" : "my first post",
    "author" : "Jim",
    "likes" : 5
},
{
    "title" : "my second post",
    "author" : "Jim",
    "likes" : 2
},
{
    "title" : "hello world",
    "author" : "Joe",
    "likes" : 3
}
Plaintext

Sample comment table

{
    "postTitle" : "my first post",
    "comment" : "great read",
    "likes" : 3
},
{
    "postTitle" : "my second post",
    "comment" : "good info",
    "likes" : 0
},
{
    "postTitle" : "my second post",
    "comment" : "i liked this post",
    "likes" : 12
},
{
    "postTitle" : "hello world",
    "comment" : "not my favorite",
    "likes" : 8
},
{
    "postTitle" : "my last post",
    "comment" : null,
    "likes" : 0
}
Plaintext

Sample “lookup”

db.posts.aggregate([
    { $lookup:
        {
           from: "comments",
           localField: "title",
           foreignField: "postTitle",
           as: "comments"
        }
    }
])
JavaScript

You can also add a pipeline and run a multi-level query in a single aggregate.

Local DB connectivity

Connect local MongoDB to your local backend application.

Here we are connecting the local MongoDB to the node.js application, on which we will execute the above operations and more using the MongoDB shell.

const mongoose = require('mongoose');
const URI = mongodb://localhost:<local port number>/<database name>;
const connectDB = async () => {
    await mongoose.connect(URI, { useUnifiedTopology: true, useNewUrlParser: true })
    console.log("connected...!")
}
module.exports = connectDB;
JavaScript

After this, you can perform different operations in your local MongoDB database.

Conclusion

As enterprise-level applications continue to evolve, MongoDB is increasingly recognized as a vital tool for data storage. If you are interested in getting started with MongoDB CLI, this article serves as a comprehensive guide to help you grasp the fundamentals of MongoDB.

Getting Started With MongoDB Shell & Basic Commands

Author
Zain Ahmed

Zain Ahmed is a Software Engineer and content creator/writer, He loves to take challenges and explore new Tech stuff. He has a vision to contribute knowledge to the challenges and explore new Tech stuff. He has a vision to contribute knowledge to the community from where he learned in his initial career.

Share this post