How to add a field with static value to MongoDB find query?


You can use $literal operator along with aggregate framework. Let us first create a collection with documents −

> db.fieldWithStaticValue.insertOne({"Name":"Larry","Age":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6554c7924bb85b3f48948")
}
> db.fieldWithStaticValue.insertOne({"Name":"Chris","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd655567924bb85b3f48949")
}
> db.fieldWithStaticValue.insertOne({"Name":"David","Age":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd655607924bb85b3f4894a")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.fieldWithStaticValue.find();

This will produce the following output −

{ "_id" : ObjectId("5cd6554c7924bb85b3f48948"), "Name" : "Larry", "Age" : 24 }
{ "_id" : ObjectId("5cd655567924bb85b3f48949"), "Name" : "Chris", "Age" : 23 }
{ "_id" : ObjectId("5cd655607924bb85b3f4894a"), "Name" : "David", "Age" : 26 }

Following is the query to add field with static value to MongoDB using $literal −

> db.fieldWithStaticValue.aggregate( [
   {
      $project: { Name: 1,Age:1, "StaticValue": { $literal: 100 } }
   }
]);

This will produce the following output −

{ "_id" : ObjectId("5cd6554c7924bb85b3f48948"), "Name" : "Larry", "Age" : 24, "StaticValue" : 100 }
{ "_id" : ObjectId("5cd655567924bb85b3f48949"), "Name" : "Chris", "Age" : 23, "StaticValue" : 100 }
{ "_id" : ObjectId("5cd655607924bb85b3f4894a"), "Name" : "David", "Age" : 26, "StaticValue" : 100 }

Updated on: 30-Jul-2019

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements