Alter in MongoDB - Add or remove column in collection - using updateMany and $set

You are here : Home / MongoDB Tutorial


Contents of page >


1) First let's create insert documents in collection in MongoDB


1.1) Let's create new collection and insert document in it before using alter to add or remove column in collection in MongoDB >
db.employee.insert({_id : 1,  firstName:"ank"})
Above will create collection (or table) (if collection already exists it will insert documents in it).


1.2) FIND > Query all documents of collection using find() method>
db.employee.find()
Output>
{ "_id" : 1, "firstName" : "ank" }

2) Add column in collection in MongoDB >
db.employee.updateMany(
   { },
   { $set: { join_date: new Date() } }
)


NOTE : updateMany was introduced in MongoDB 3.2


Sql query equivalent to above MongoDB query is >
We will use alter command.
ALTER TABLE employee
ADD join_date DATETIME


3) Add column in collection in MongoDB >


db.employee.updateMany(
   { },
   { $unset: { "join_date": "" } }
)


NOTE : updateMany was introduced in MongoDB 3.2


Sql query equivalent to above MongoDB query is >
We will use alter command.
ALTER TABLE employee
DROP COLUMN join_date

4) Summary -
So in this MongoDB tutorial we learned how to Alter in MongoDB.
Add column in collection in MongoDB >
db.employee.updateMany(
   { },
   { $set: { join_date: new Date() } }
)


Add column in collection in MongoDB >
db.employee.updateMany(
   { },
   { $unset: { "join_date": "" } }
)


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.


RELATED LINKS>

Labels: MongoDB
eEdit
Must read for you :