Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to create new field and count set the count of another field in it?
To create a new field and count elements from another field in MongoDB, use $addFields with $map and $size operators. This allows you to transform array elements and count their sizes in a single aggregation.
Syntax
db.collection.aggregate([
{
"$addFields": {
"arrayField": {
"$map": {
"input": "$arrayField",
"as": "element",
"in": {
"existingField": "$$element.existingField",
"newCountField": { "$size": "$$element.arrayToCount" }
}
}
}
}
}
]);
Sample Data
db.demo429.insertOne({
"_id": 101,
"Value": 3,
"details": [
{
"Age": 29,
"Value": 3,
"details1": [1, 2, 3]
},
{
"Age": 31,
"Value": 4,
"details1": [354]
}
]
});
Example: Count Array Elements
Create a new field NumberOfDetails1 that counts elements in the details1 array ?
db.demo429.aggregate([
{
"$addFields": {
"details": {
"$map": {
"input": "$details",
"as": "d",
"in": {
"Age": "$$d.Age",
"NumberOfDetails1": { "$size": "$$d.details1" }
}
}
}
}
}
]);
{
"_id": 101,
"Value": 3,
"details": [
{ "Age": 29, "NumberOfDetails1": 3 },
{ "Age": 31, "NumberOfDetails1": 1 }
]
}
How It Works
-
$addFieldsadds or modifies fields in documents -
$maptransforms each element in the array -
$sizecounts the number of elements in an array -
$$drefers to the current element being processed
Conclusion
Use $addFields with $map and $size to create new fields containing counts of array elements. This approach transforms nested arrays while preserving the document structure and adding computed count fields.
Advertisements
