How to add a new field to all the documents in a MongoDB collection

MongoDBDatabaseBig Data Analytics

To add a new field, use $addFields in MongoDB. Let us create a collection with documents −

> db.demo712.insertOne({"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85f675d33e20ed1097b82")
}
> db.demo712.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85f6a5d33e20ed1097b83")
}
> db.demo712.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85f6e5d33e20ed1097b84")
}

Display all documents from a collection with the help of find() method −

> db.demo712.find();

This will produce the following output −

{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John" }
{ "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris" }
{ "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob" }

Following is the query to add a new field −

> db.demo712.aggregate([
...    {
...       $addFields:
...       {
...          "TeacherName":"Robert"
...       }
...    }
... ]
... );

This will produce the following output −

{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John", "TeacherName" : "Robert" }
{ "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris", "TeacherName" : "Robert" }
{ "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob", "TeacherName" : "Robert" }
raja
Published on 14-May-2020 13:35:38
Advertisements