MongoDB Commands: A Beginner's Guide to Talking to Your Database

MongoDB Commands: A Beginner's Guide to Talking to Your Database

Introduction :

MongoDB is a NoSQL database which means it stores data in object form (key & value pair). It is known for its easy understanding, usability & flexibility.
However, if you're new to MongoDB, it can be overwhelming to know where to start. In this blog post, we'll cover basic to intermediate MongoDB commands you need to know to get started with this powerful database.

Requirements :

  • MongoDB Server : To handle client connection & database tasks.

  • MongoDB Shell : To provide the functionality to communicate with the database using CLI.

  • MongoDB Compass : To provide a UI interface for looking into Database (Not Medentary).

( Note: You can download all the above tools from the official MongoDB website & set up the environmental variables. )

Let's Start :

1. Start database server : Open cmd or terminal & enter the command as "mongod".

2. Start MongoDB shell : Open another cmd or terminal & enter the command as "mongosh".

Creation Commands :

  • View a Databases:

      show databases
    
  • Creating a new Database:

      use ecommerce
    
  • Creating a new Collection:

      db.createCollection("product")
    
  • View a Collections:

      show collections()
    

Insertion Commands :

  • Insert Single Object:

      db.insertOne( {
          title:"Iphone 12",
          price: 200000,
          images:[ "url1" ,"url2"]
      })
    
  • Insert Multiple Object:

      db.insertOne( [
         { 
          title:"Iphone 12",
          price: 200000,
          images:[ "url1" ,"url2"]  
         },
         { 
          title:"Iphone 12",
          price: 200000,
          images:[ "url1" ,"url2"]  
         }
      ])
    

View Commands :

  • Querying Data :

      db.products.find()
    
  • Query Criteria :

      db.collection.find({ name:"john" }) 
      // or //
      db.collection.find( { name:{ $eq:"john"}})
    

    We can use $gt, $gte, $lt, and $lte to check conditions like greater than, greater than equal to, lower than, and lower than equal to, respectively.

  • Query Logical Condition:

      db.collection.find({$and: [ {name:{ $eq:"john"}} , {age :{$gte:20}} ] })
    

    We can use $or, $not, $nor in place of $and which perform logical OR, NOT, NOR operation.

  • Querying Sorted Data :

      db.collection.find( name:"john").sort(rating:1)
    

    Sort data by rating in increasing order use rating:1, for decreasing order use rating: -1.

  • Querying Limited Data :

      db.collection.find({ name:"john" }).sort({ rating:1 }).limit(3)
    
  • Querying Projection:

      db.collection.find({ age:{$gt:20} } ,{name:1, address:1 ,_id:0} )
    

    Only show only the name & address field for filtered data.

  • Count Documents:

    Use db.collection.countDocuments() to get number of document. The below command count documents for particular criteria specified by the user.

      db.collection.countDocuments({ age:{$gt:20} })
      //output : 5
    

Update Commands :

  • Single Update Data :
db.products.updateOne( {id:7} ,{ $set:{price:40000} } )
// replace previous price value of id=7 to 40000

If the object inside the $set does not exist then it inserts this object into a document having id 7. so, used it carefully.

  • Multiple Update Data :

      db.products.updateMany( {id:{$gt:7 }} ,{ $set:{price:40000} } )
      // replace all previous price value of id >= 7 to 40000
    
  • Update & Insert Both:

      db.products.updateMany( {id:{$gt:7 }} ,{ $set:{price:40000} },{upsert:true} )
      // If id=7 document not exist it create another document with item id and price
      // else it update value of price to 40000
    
  • Replace Document :

      db.products.replaceOne( {id:7 } ,{price:40000 ,name:"coder"} )
      //If id=7 exist then replace all field & save price,name fields
      // else nothing will do
    

Delete Commands :

  • Delete Single Document :

      db.products.deleteOne( {id:7 } )
      //Delete first full document which has id =7.
    
  • Delete Multiple Documents:

      db.products.deleteMany( {price:7000} )
      //Delete Multiple full document which has price = 7000.
    

Conclusion :

In this blog post, we covered the basic and intermediate MongoDB commands you need to know to get started with this powerful database. We covered creating a database and collection, inserting data, querying data, updating data, and deleting data. With these commands, you'll be able to start building your own MongoDB applications in no time.