To add a column, you need to update the collection. The syntax is as follows −
db.getCollection(yourCollectionName).update({}, {$set: {"yourColumnName": "yourValue"}},false,true);
To understand the above syntax, let us create a collection with documents −
> db.addColumnDemo.insertOne({"StudentId":101,"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e04d66af5e889d7a519950f") } > db.addColumnDemo.insertOne({"StudentId":102,"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e04d673f5e889d7a5199510") } > db.addColumnDemo.insertOne({"StudentId":103,"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e04d67bf5e889d7a5199511") }
Following is the query to display all documents from a collection with the help of find() method −
> db.addColumnDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e04d66af5e889d7a519950f"), "StudentId" : 101, "StudentName" : "Chris" } { "_id" : ObjectId("5e04d673f5e889d7a5199510"), "StudentId" : 102, "StudentName" : "Robert" } { "_id" : ObjectId("5e04d67bf5e889d7a5199511"), "StudentId" : 103, "StudentName" : "David" }
Here is the query to add a column in MongoDB −
> db.getCollection('addColumnDemo').update({}, {$set: {"StudentCityName": "New York"}},false,true); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
Following is the query to display all documents from a collection with the help of find() method −
> db.addColumnDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e04d66af5e889d7a519950f"), "StudentId" : 101, "StudentName" : "Chris", "StudentCityName" : "New York" } { "_id" : ObjectId("5e04d673f5e889d7a5199510"), "StudentId" : 102, "StudentName" : "Robert", "StudentCityName" : "New York" } { "_id" : ObjectId("5e04d67bf5e889d7a5199511"), "StudentId" : 103, "StudentName" : "David", "StudentCityName" : "New York" }