MongoDB query to sort by the sum of specified object inside inner array?


To sort by the sum of specified object inside inner array, use $match along with $sort. Let us create a collection with documents −

> db.demo189.insertOne(
...   {
...      "_id" : 100,
...      "List" : [
...         {
...            "Value" : 10
...         },
..         .{
...            "Value" : 20
...         },
...         {
...            "Value" : 10
...         }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 100 }
> db.demo189.insertOne(
...   {
...      "_id" : 101,
...      "List" : [
...         {
...            "Value" : 10
...         },
...         {
...            "Value" : 10
...         },
...         {
...            "Value" : 10
...         }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 101 }

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

> db.demo189.find();

This will produce the following output −

{ "_id" : 100, "List" : [ { "Value" : 10 }, { "Value" : 20 }, { "Value" : 10 } ] }
{ "_id" : 101, "List" : [ { "Value" : 10 }, { "Value" : 10 }, { "Value" : 10 } ] }

Following is the query to sort by the sum of specified object inside inner array − 

> db.demo189.aggregate([
...   { "$unwind" : "$List" },
...   { "$group" : {
...      "_id" : "$_id",
...      "total" : {
...         "$sum" : {
...            "$cond" : {
...               "if" : { "$eq" : [ "$List.Value", 10 ] },
...                  "then" : 1,
...               "else" : 0
...            }
...         }
...      },
...      "List" : {
...         "$push" : {
...            "Value" : "$List.Value"
...         }
...      }
...   }},
...   { "$sort" : { "total" : -1 } },
...   { "$project" : {
...      "List" : 1
...   }}
...])

This will produce the following output −

{ "_id" : 101, "List" : [ { "Value" : 10 }, { "Value" : 10 }, { "Value" : 10 } ] }
{ "_id" : 100, "List" : [ { "Value" : 10 }, { "Value" : 20 }, { "Value" : 10 } ] }

Updated on: 27-Mar-2020

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements