Mongo commands every Developer should know.

Mongo commands every Developer should know.

Create, Update & Querying MongoDB

Following are some of the basic MongoDB commands to get started with mongo. I will show you how to create, update and query your first database.

Creating Database

You can create a database using use testdb. Then you can add your documents using insertOne or insertMany. I have created a simple JSON file here with some sample data.

Untitled.png

A sample template if you want to copy it.


[
    {
        "_id" : 1, 
        "name": "mack", 
        "age" : 25, 
        "email" : "xyz@gmail.com", 
        "interest" : {
            "name" : "painting", 
            "type" : "art"
        }, 
        "skills" : ["mongodb", "mysql"]
    }, 

    {
        "_id" : 2, 
        "name": "jon", 
        "age" : 23, 
        "email" : "jon@gmail.com", 
        "interest" : {
            "name" : "running", 
            "type" : "sports"
        }, 
        "skills" : ["mongodb", "mysql"]
    }, 

    {
        "_id" : 3, 
        "name": "mark", 
        "age" : 34, 
        "email" : "jon@gmail.com", 
        "interest" : {
            "name" : "robots", 
            "type" : "tech"
        }, 
        "skills" : ["mongodb", "mysql"]
    }, 

    {
        "_id" : 4, 
        "name": "irfa", 
        "age" : 24, 
        "email" : "irfa@gmail.com", 
        "interest" : {
            "name" : "robots", 
            "type" : "tech"
        }, 
        "skills" : ["robotics", "mysql"]
    }, 

    {
        "_id" : 5, 
        "name": "henry", 
        "age" : 24, 
        "email" : "henry@gmail.com", 
        "interest" : {
            "name" : "swimming", 
            "type" : "sports"
        }, 
        "skills" : ["js", "mysql"]
    }, 

    {
        "_id" : 6, 
        "name": "jack", 
        "age" : 24, 
        "email" : "jack@gmail.com", 
        "interest" : {
            "name" : "painting", 
            "type" : "art"
        }, 
        "skills" : ["flask", "django"]
    }

]

Now adding these objects using insertMany

Untitled.jpeg

I have added IDs manually but you don’t have to add them mongo will do it for you.

Untitled 1.jpeg

You can see all the objects are been added with the desired IDs I specified. If you didn’t specify an id, don’t worry mongo will add the random ids for your documents.

Updating Documents

There are different methods used in order to update a document depending on our needs. Following are some operators which will help you update the document

$set

The $set operator replaces the value of a field with the specified value.

db.student.updateOne(
   { _id: 1 },
   { $set:
      {
        name: "mikeTyson",
        email : "mikeTyson@gmail.com", 
        interest : {
            name : "boxing", 
            type : "sport"
        }, 
        skills : ["boxing", "fighting"]
      }
   }
)

This will set the existing fields in the document where id equals 1.

Untitled 2.jpeg

You can then use db.collection.find() to see the result. You can see that the object has been updated now. Use db.collection.find().pretty() that will help you reading the object on the terminal easily.

$addToSet

If you wanna add some new value to an array in the object use addToSet operator. The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

db.student.updateOne(
   { _id: 1 },
   { $addToSet:
      {
        skills : "legend"
      }
   }
)

This will add a new element to our skills array.

Untitled 3.jpeg

See legend has now been added to the array.

$push

It helps push new values to the array in a single instance or many. The $push operator appends a specified value to an array.

db.student.updateOne(
   { _id: 1 },
   { $push:
        {
            skills : "legendry"
        } 
    }
)

Untitled 4.jpeg

$pull

push and pull operators make dealing with the arrays updates easy. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

db.student.updateOne(
   { _id: 1 },
   { $pull:
        {
            skills : "legendry"
        } 
    }
)

Untitled 5.jpeg

Querying your Collection

Now you wanna extract information about a specific person/object 🤔. Don’t worry just go ahead and use these operators 😀.

find()

Use this if you wanna find all the documents that match the condition.

db.student.find({"interest.type" : "tech"}).pretty()

db.student.find({age : { $lt : 25 }}).pretty()

Untitled 6.jpeg

Untitled 7.jpeg

findOne()

It will return the first document that matches the condition specified.

db.student.findOne({age : { $lt : 25 }}).pretty()

Untitled 8.jpeg

You can see it just returned the first document having an age less than 25.

Limiting using limit()

While querying your documents use limit() to specify how many matching documents to be returned.

db.student.find({age : { $lt : 25 }}).limit(2).pretty()

Untitled 9.jpeg

Sorting using sort()

It helps sort the resulting documents with respect to the specified field.

db.student.find().sort({age : -1}).pretty()

It will sort the result with decreasing ages i.e. descending order.

Untitled 10.jpeg

db.student.find().sort({age : -1}).pretty()

Untitled 11.jpeg

So that was it. Follow me for more 😀. Also, read me at theundersurfers.netlify.app


Originally published at theundersurfers.netlify.app