MongoDB query to create new field and count set the count of another field in it?

MongoDBDatabaseBig Data Analytics

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 } ] }
raja
Published on 03-Apr-2020 14:04:21
Advertisements