MongoDB $unwind to get the count

MongoDBDatabaseBig Data Analytics

The $unwind in MongoDB deconstructs an array field from the input documents to output a document for each element. Use $unwind along with aggregate() to get the count. Let us create a collection with documents −

> db.demo478.insertOne(
... {
...
...    "Details" : {
...       _id:1,
...       "Information" : [
...          {
...             "Name" : "Chris",
...             "Age":21
...          },
...          {
...             "Name" : "David",
...             "Age":23
...          },
...          {
...
...             "Name" : null,
...             "Age":22
...          },
...          {
...
...             "Name" : null,
...             "Age":24
...          }
...       ]
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8204acb0f3fa88e2279092")
}
>
> db.demo478.insertOne(
... {
...
...    "Details" : {
...       _id:2,
...       "Information" : [
...          {
...             "Name" : "Bob",
...             "Age":21
...          },
...          {
...             "Name" : null,
...             "Age":20
...          }
...       ]
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8204adb0f3fa88e2279093")
}

Display all documents from a collection with the help of find() method −

> db.demo478.find();

This will produce the following output −

{ "_id" : ObjectId("5e8204acb0f3fa88e2279092"), "Details" : { "_id" : 1, "Information" : [ {
"Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : null, "Age" : 22 }, {
"Name" : null, "Age" : 24 } ] } }
{ "_id" : ObjectId("5e8204adb0f3fa88e2279093"), "Details" : { "_id" : 2, "Information" : [ {
"Name" : "Bob", "Age" : 21 }, { "Name" : null, "Age" : 20 } ] } }

Following is the query to implement $unwind to get the count −

> db.demo478.aggregate([
...    { "$unwind": "$Details.Information" },
...    {
...       "$group" : {
...          "_id": "$Details.Information.Age",
...          "count" : {
...             "$sum": {
...                "$cond": [
...                   { "$gt": [ "$Details.Information.Name", null ] },
...                   1, 0
...                ]
...             }
...          }
...       }
...    },
... { "$sort" : { "count" : -1 } }
... ])

This will produce the following output −

{ "_id" : 21, "count" : 2 }
{ "_id" : 23, "count" : 1 }
{ "_id" : 24, "count" : 0 }
{ "_id" : 20, "count" : 0 }
{ "_id" : 22, "count" : 0 }
raja
Published on 11-May-2020 09:49:43
Advertisements