Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ] }Advertisements