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"
}


No comments:

Post a Comment

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