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

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: 2020-03-27T08:22:39+05:30

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements