- 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 create new field and count set the count of another field in it?
For new field, use $addFields in MongoDB. The $addFields is used to add new fields to documents. Let us create a collection with documents −
> db.demo429.insertOne( ... { ... "_id": 101, ... "Value": 3, ... "details": [ ... { ... "Age": 29, ... "Value": 3, ... "details1": [ ... 1, ... 2, ... 3 ... ] ... }, ... { ... "Age": 31, ... "Value": 4, ... "details1": [ ... 354 ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo429.find();
This will produce the following output −
{ "_id" : 101, "Value" : 3, "details" : [ { "Age" : 29, "Value" : 3, "details1" : [ 1, 2, 3 ] }, { "Age" : 31, "Value" : 4, "details1" : [ 354 ] } ] }
Following is the query to create new field and set the count of other field −
> db.demo429.aggregate([ ... { ... "$addFields": { ... "details" : { ... "$map": { ... "input": "$details", ... "as": "d", ... "in": { ... "Age" : "$$d.Age", ... "NumberOfDetails1": { "$size": "$$d.details1" } ... } ... } ... } ... } ... } ... ])
This will produce the following output −
{ "_id" : 101, "Value" : 3, "details" : [ { "Age" : 29, "NumberOfDetails1" : 3 }, { "Age" : 31, "NumberOfDetails1" : 1 } ] }
Advertisements