![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
" }
Advertisements