Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongodb – order by the sum of size of multiple arrays

I have a collection with documents structured like this:

{
    "company": "abc",
    "countries": {
        "australia": ["banana", "kiwi", "avocado"],
        "germany": ["apple", "cucumber"],
        "columbia": ["banana"]
    }
}

Question:

How can i find all documents sorted by the sum of the length of all arrays in "countries" ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the provided example, the sum would be 6.

The keys in countries may only contain a subset, so in in this example it is australia, germany and columbia, but in another document it may just be australia or germany and columbia.

Thanks for your help!

>Solution :

One option is to use $reduce to calculate this value for each document:

db.collection.aggregate([
  {$set: {
      count: {$reduce: {
          input: {$objectToArray: "$countries"},
          initialValue: 0,
          in: {$add: ["$$value", {$size: "$$this.v"}]}
      }}
  }},
  {$sort: {count: -1}},
  {$unset: 'count'}
])

See how it works on the playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading