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

To add a new field and concatenate price results divided by a specific number in MongoDB, use the $addFields stage with $reduce and $map operators to process array values and combine them into a single string.

Syntax

db.collection.aggregate([
    {
        $addFields: {
            newField: {
                $reduce: {
                    input: { $map: { input: "arrayPath", in: { $toString: { $divide: ["$$this", divisor] } } } },
                    initialValue: "",
                    in: { $concat: ["$$value", "$$this", "separator"] }
                }
            }
        }
    }
]);

Sample Data

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

Example

Add a new field that contains price values divided by 5 and concatenated with line breaks ?

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

How It Works

  • $map processes each price in the array, divides by 5, and converts to string
  • $reduce combines all processed values into a single concatenated string
  • $project selects only the desired fields in the output

Conclusion

Use $addFields with $reduce and $map to create new fields that contain processed and concatenated values from nested arrays. This approach allows complex transformations and string manipulations in a single aggregation pipeline.

Updated on: 2026-03-15T03:50:23+05:30

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements