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 } ] }

Updated on: 03-Apr-2020

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements