Showing posts with label MongoDB Query. Show all posts
Showing posts with label MongoDB Query. Show all posts

How to Rename Document field in MongoDB and $rename Operator

Rename the Document field in mongoDB

 Sometime We want to Rename the Document field in Collection MongoDB using $rename Operator. Again by using collection method we can do it easily. whenever we want to rename the document field we have to use $rename operator.

db.collectionName.update( criteria, objNew, upsert, multi )

Criteria : This will hold the criteria for updating the document. Here you can specify the condition whether you want to update all the document or few document in collection.

objNew :  $operator which will manipulate the object.

upsert : It is Upsert Operation which will insert the record if it doesn't exist.

multi : Indicates matched documents criteria should be updated or just one Document.


MongoDB Rename Document field


Step 1 :  Create DB and Collection

Create studentInfo DB in mongoDB using below command as well as create student collection and insert Document in it.

create DB and implement rename operator
  

                       

Now we will have some document sample from student collection. By using below query we will fetch document.

db.student.find().pretty()

Output of Above query is below.

{
        "_id" : ObjectId("5ebeaafd50845b5c0ea8bf54"),
        "id" : 1,
        "name" : "M Kumar",
        "dob" : "2003-04-07",
        "marks" : 54,
        "created_at" : "2017-11-13 23:33:42",
        "isOpen" : false,
        "status" : 1
}
{
        "_id" : ObjectId("5ebeaafd50845b5c0ea8bf55"),
        "id" : 2,
        "name" : "MOHAMMED ISHAQ  H",
        "dob" : "2002-06-14",
        "marks" : 67,
        "created_at" : "2016-11-13 23:33:42",
        "isOpen" : false,
        "status" : 1,
        "exam_status" : "PASSED"
}

Rename the Document field "name" as "fullName"


In the above document we will rename the field "name" using below query which uses $rename operator to do that.

db.student.update({},{$rename :{"name":"fullName"}}, false, true)

This above query will rename the document filed. after executing this we will fetch the document again. Output is below.

{
        "_id" : ObjectId("5ebeaafd50845b5c0ea8bf54"),
        "id" : 1,
        "dob" : "2003-04-07",
        "marks" : 54,
        "created_at" : "2017-11-13 23:33:42",
        "isOpen" : false,
        "status" : 1,
        "fullName" : "M Kumar"
}
{
        "_id" : ObjectId("5ebeaafd50845b5c0ea8bf55"),
        "id" : 2,
        "dob" : "2002-06-14",
        "marks" : 67,
        "created_at" : "2016-11-13 23:33:42",
        "isOpen" : false,
        "status" : 1,
        "exam_status" : "PASSED",
        "fullName" : "MOHAMMED ISHAQ  H"
}


MongoDB Crud Operation and Mongo DB Crud

MongoDB Crud Operation

MongoDB Crud Operation Basics


Create studentInfo Database in MongoDB server. Use the below code for creating the DB.


Above use studentInfo command will create the DB in MongoDB Server. If studentInfo DB will exist then it will switch to that instead of creating it. To view the created database in the list you must have to create at least one collection in that.

MongoDB provide db.createCollection() method to create collection in database. Command to create studnet collection in studentInfo Database is below 


Press Enter collection will be created in studentInfo Database with the name of student. To view all the collection in the studentInfo Database use below command. Below command will list all the collection present in the studentInfo Database. 

Insert or Create Document in MongoDb Collection


To insert document in the collection in MongoDB Database. We use below two command to insert the document.

  • db.collectionName.insertOne()
  • db.collectionName.insertMany()

Using above two method we will insert the document in the student Collection of studentInfo Database. 

This below command will insert one document in student Collection.

db.student.insertOne(
   { 
     "id":1,
     "name":"Manoj Kumar",
     "dob":"2003-04-07",
     "marks":54,
     "created_at":"2017-11-13 23:33:42"
   }
)

To Insert many document at a time we have to use db.collectionName.insertMany() method . Below is the code for inserting many document at a time. We can pass all the document as a array.

db.student.insertMany([
   { 
     "id":2,
     "name":"MOHAMMED  H",
     "dob":"2002-06-14",
     "marks":67,
     "created_at":"2016-11-13 23:33:42"
   },
   { 
     "id":3,
     "name":"ANBUSELVAM S",
     "dob":"2004-06-18",
     "marks":87,
     "created_at":"2019-11-13 23:33:42"
   }
 ])



Fetch Or Retrieve Document from Collection


To retrieve or fetch the document from the MongoDB collection we use db.collectionName.find() method.
  • db.student.find() method will fetch all the document from the specified MongoDB collection. This above method will fetch all the document in single line which will not be in readable format.
  • db.student.find().pretty() method will fetch and arrange the collection document in some proper readable format. pretty() method will give you the output is below for reference. 

MongoDB Operators and Query Example


We can apply various filter on mongoDB collection document based on certain condition. We can use various operator also for document filter. Below is the query list and condition to demonstrate the filtration.

$eq (=)
$eq will match the value with specified value.
$gt (>)
$gt will check that the value is greater than specified value.
$gte (>=)
$gte will check that the value is greater than equal to specified Value.
$in (IN)
$in will check that specified value is there in range or not.
$nin (NOTIN)
$nin will check that specified value not lies in the range.
$lt (<)
$lt will check that the value is less than the specified value
$lte (=<)
$lte will check that the value is less than the specified value
$ne (!=)
$ne will check whether the value not equal to specified value


$and
Logical AND join multiple query clause and compare multiple clause and return value as True or False.
$not
Logical NOT Check the query expression and return the result.
$nor
Logical NOR join multiple query clause and compare multiple clause
$or
Logical OR  join multiple query clause and compare multiple clause and return value as True or False

Some Query Example using above operator is below for reference with output.

  •  db.student.find({marks:{$eq:43}}).pretty()     O/P is below                                                                                             
    mongoDB Comparision Operator Example

  • db.student.find({marks :{$gte:70}}).pretty()  O/P is below                                                                                 
    $gte operator in MongoDB

  • db.student.find({marks :{$in:[54, 87]}}).pretty()  O/P is below                                                                         

Query Using AND Logical Operator in MongoDB


  • db.student.find({$and :[{name : "JAGAN J"},{marks :98}]}).pretty()                                               {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf58"),
            "id" : 5,
            "name" : "JAGAN J",
            "dob" : "2003-04-10",
            "marks" : 98,
            "created_at" : "2012-11-13 23:33:42"
        }


Query Using OR Logical Operator in MongoDB

  • db.student.find({$or :[{name:"JAGAN J"},{marks :{$gt:70}}]}).pretty()                                     {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf56"),
            "id" : 3,
            "name" : "ANBUSELVAM S",
            "dob" : "2004-06-18",
            "marks" : 87,
            "created_at" : "2019-11-13 23:33:42"
    }
    {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf58"),
            "id" : 5,
            "name" : "JAGAN J",
            "dob" : "2003-04-10",
            "marks" : 98,
            "created_at" : "2012-11-13 23:33:42"
    }

Query Using AND Operator as well as OR in MongoDB


  • db.student.find({marks :{$lt : 99}, $or :[{marks :{$in:[43,98]}},{name : "JAGAN J"}]}).pretty()                                                                                                                                  {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf57"),
            "id" : 4,
            "name" : "MARTINPRIYADOSS J",
            "dob" : "2004-03-08",
            "marks" : 43,
            "created_at" : "2012-11-13 23:33:42"
    }
    {
            "_id" : ObjectId("5ebeaafd50845b5c0ea8bf58"),
            "id" : 5,
            "name" : "JAGAN J",
            "dob" : "2003-04-10",
            "marks" : 98,
            "created_at" : "2012-11-13 23:33:42"
    }

MongoDB Update Query

Update query in MongoDB is done using below method.
  • db.collection.updateOne() 
  • db.collection.updateMany() 
  • db.collection.replaceOne()

Delete Operation In MongoDB

Delete Query in MongoDB is done using below method.
  • db.collection.deleteOne() 
  • db.collection.deleteMany() 

MongoDB Basic Command and noSql Query

MongoDB Basic Command and Installation

MongoDB is document based NoSql Database written in C++.

Before Learning MongoDB we must have the basic idea of SQL vs NoSqL.

Difference Between SQL and NOSQL




SQL(Structured Query Language)
  • SQL database is primarily known as RDBMS (Relational Database Management System) which is table based Database. Data is Stored in Table.
  • SQL database is vertically Scalable. Oracle, Postgres, MsSql etc is example of RDBMS.
NOSQL
  • NOSQL database is primarily known as Non Relational Database or distributed Database which store the data in the form of document or key value pair etc.
  • NOSQL is Horizontally scalable, MongoDB, Redis, NEO4J is NOSQL Database Example. 

Before Using MongoDB You must know the basic command to run, View and execute the query on command prompt. First Install the MONGODB Server.


  • Command to run the MongoDB Server
                 âžĄ mongod  (Type this Command and press Enter)

  • To Check the Version of MongoDB Installed 
                 âžĄ mongo --version  (Type this Command and press Enter)

  • To Start the MongoDB Type the Command in Cmd Prompt
                 âžĄ mongo  (Type this Command and press Enter)

  • Command to Create DB in Mongo
                 âžĄ use db-name  (db-name can be anything Type this Command and press Enter)

  • To Check the Status of Created Database In MongoDB
                 âžĄ show dbs  ( Type this Command and press Enter)

Note : Once we use the above command to know the status of Database creation. Our newly created database will not come in the list because it do not contain any collection.

So Once you create the Database in MongoDB create few collection in that then by using  âžĄ show dbs command you can see the DB created by you in the list. Once you create the collection you can view the list of Database.
  • To use particular DB from the list use this command, by default test DB is used.
                  ➥ use db-name  ( Type this Command and press Enter)

  • Command to know the current DB which is used

                  ➥ db  ( Type this Command and press Enter)


How to create the collection in MongoDB

  • Command to Create the collection in MongoDB

                    ➥ db.createCollection("  Collection-Name ")  ( Type this Command and press Enter)


  • Command to Show all the collection Created In Mongo Database

                    ➥ show collections  ( Type this Command and press Enter)


  • How to Drop the collection From The MongoDB

                    ➥ db.collection-name.drop()  ( Type this Command and press Enter)


  • How to Drop any Database created in MongoDB

                     âžĄ db.dropDatabase()  ( Type this Command and press Enter)


Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post