

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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", " \n "] } ... } ... } ... } ... }, ... { ... $project: { ... _id: 0, ... Number:1, ... productPriceList:1 ... } ... } ... ])
This will produce the following output −
{ "Number" : "7374644", "productPriceList" : "100 \n 400 \n " }
- Related Questions & Answers
- MongoDB query to add up the values of a specific field in documents
- MongoDB query to create new field and count set the count of another field in it?
- “Structured” grouping query in MongoDB to display result with a new field displaying the count
- MongoDB query to count the number of array items in documents and display in a new field
- Add new field to every document in a MongoDB collection?
- MongoDB query select and display only a specific field from the document?
- How to add a new field to all the documents in a MongoDB collection
- MongoDB query (aggregation framework) to match a specific field value
- MySQL SELECT to add a new column to a query and give it a value?
- Search by specific field in MongoDB
- MongoDB query by sub-field?
- MongoDB query to get a specific number of items
- Return a specific field in MongoDB?
- How to run MongoDB query to update only a specific field value?
- Find the document by field name with a specific value in MongoDB?
Advertisements