MongoDB query to add a new field and concatenate the price result divided by a specific number in it


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

> db.demo719.insertOne(
...    {
...       "Number":"7374644",
...       "details" : {
...          "otherDetails" : [
...             {
...                "ProductId" :"102",
...                "ProductPrice" : NumberInt(500)
...             },
...             {
...                "ProductId" :"103",
...                "ProductPrice" : NumberInt(2000)
...             }
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eaae56c43417811278f5882")
}

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

> db.demo719.find();

This will produce the following output −

{ "_id" : ObjectId("5eaae56c43417811278f5882"), "Number" : "7374644", "details" : { "otherDetails" : [ { "ProductId" : "102", "ProductPrice" : 500 }, { "ProductId" : "103", "ProductPrice" : 2000 } ] } }

Following is the query to add a new field and concatenate the price result divided by a specific number in it −

> db.demo719.aggregate([
...    {
...       $addFields:{
...          productPriceList: {
...             $reduce: {
...                input: {
...                   $map: {
...                      input: "$details.otherDetails.ProductPrice",
...                      in: { $toString: { $divide: ["$$this", 5] } }
...                   }
...                },
...                initialValue: "",
...                in: { $concat: ["$$value", "$$this", " 
"] } ...             } ...          } ...       } ...    }, ...    { ...       $project: { ...          _id: 0, ...          Number:1, ...          productPriceList:1 ...       } ...    } ... ])

This will produce the following output −

{ "Number" : "7374644", "productPriceList" : "100 
400
" }

Updated on: 15-May-2020

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements