0

I have this example MongoDB entry in a users DB:

{
     _id: xxx,
     name: "name",
     files:[{
          fileName: "test",
          size: 50
          },
          {
          fileName: "test2",
          size: 44
          },
          {
          fileName: "test3",
          size: 120
          }
     ]
}

And I'm trying to use Pymongo to sort the files by size.

How can I sort the dictionaries , using the aggregate command? In other words, I want it to output this, in this case, in descending order:

[
     {
          fileName: "test3",
          size: 120
     },
     {
          fileName: "test",
          size: 50
     },
     {
          fileName: "test2",
          size: 44
     }
]

I can't find a way to get just the array itself and turn it into a Python list, so I can then sort it outside of using the Pymongo library, which is why I'm looking into using the Pymongo library to do the job.

Tasos500
  • 107
  • 2
  • 11
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Matias Lopez Sep 26 '22 at 12:18
  • Not really. For me to be able to just use this, I'd have to first get the array itself using `aggregate`, something I'm not sure how to do. – Tasos500 Sep 26 '22 at 12:33
  • The way I would do it is first to access the key of the dictionary `files = body['files']`, sort with `files_sorted = sorted(files, key=lambda d: d['size'])`, and then dump it to bson. Does that work for you? – Matias Lopez Sep 26 '22 at 12:57

1 Answers1

0

This is the solution I made. It does exactly what I needed.

db.users.aggregate([
  {
    "$unwind": "$files"
  },
  {
    "$sort": {
      "files.size": 1
    }
  },
  {
    "$replaceRoot": {
      newRoot: "$files"
    }
  }
])

And here it is in action: https://mongoplayground.net/p/4v0m02PsbfQ

Tasos500
  • 107
  • 2
  • 11