Replace value with a string literal during MongoDB aggregation operation

MongoDBDatabaseBig Data Analytics

Use MongoDB $literal to set a string literal. Let us first create a collection with documents −

>db.replacevaluedemo.insertOne({"StudentName":"Chris","StudentFavouriteSubject":{"TeacherName":"Bob","SubjectCode":"MySQL111"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0390a3f5e889d7a51994fd")
}
>db.replacevaluedemo.insertOne({"StudentName":"Mike","StudentFavouriteSubject":{"TeacherName":"David","SubjectCode":"3221Java"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0390b8f5e889d7a51994fe")
}

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

> db.replacevaluedemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e0390a3f5e889d7a51994fd"),
   "StudentName" : "Chris",
   "StudentFavouriteSubject" : {
      "TeacherName" : "Bob",
      "SubjectCode" : "MySQL111"
   }
}
{
   "_id" : ObjectId("5e0390b8f5e889d7a51994fe"),
   "StudentName" : "Mike",
   "StudentFavouriteSubject" : {
      "TeacherName" : "David",
      "SubjectCode" : "3221Java"
   }
}

Here is the query to replace value with a string literal −

> db.replacevaluedemo.aggregate([{
...    "$project": {
...       "_id": 1,
...       "StudentFavouriteSubject": {
...          SubjectCode: 1,
...          TeacherName: { $literal: "UNKNOWN NAME" }
...       }
...    }
... }]).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e0390a3f5e889d7a51994fd"),
   "StudentFavouriteSubject" : {
      "SubjectCode" : "MySQL111",
      "TeacherName" : "UNKNOWN NAME"
   }
}
{
   "_id" : ObjectId("5e0390b8f5e889d7a51994fe"),
   "StudentFavouriteSubject" : {
      "SubjectCode" : "3221Java",
      "TeacherName" : "UNKNOWN NAME"
   }
}
raja
Published on 27-Mar-2020 11:39:37
Advertisements