

- 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 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 } ] }
- Related Questions & Answers
- MongoDB query to count the number of array items in documents and display in a new field
- MongoDB query to update array with another field?
- “Structured” grouping query in MongoDB to display result with a new field displaying the count
- Update MongoDB field using value of another field?
- MySQL query to get the count of all the elements in the field?
- MongoDB aggregate to get the count of field values of corresponding duplicate names?
- How to count and sum a field between 2 dates in MongoDB?
- MongoDB query to add a new field and concatenate the price result divided by a specific number in it
- Count boolean field values within a single MySQL query?
- MySQL query to count comma’s from field value?
- MongoDB query by sub-field?
- How to count number of distinct values per field/ key in MongoDB?
- MongoDB query to convert the field value and create datetime day of month during projection?
- MongoDB query for counting number of unique fields grouped by another field?
- How can I aggregate collection and group by field count in MongoDB?
Advertisements