How to query and sort nested mongodb information in python?

I have the following code:

myd = mergedCollection.find(myquery).sort("Price")
print("MY D: "+str(myd))
shoes = myd[0]["theAssociatedShoes"]
print("Shoes: "+ str(shoes))

With the output:

MY D: <pymongo.cursor.Cursor object at 0x05859538>
Shoes: [{'Title': 'Nike Cosmic Unity "Amalgam"', 'Price': 160, 'Currency': 'USD', 'Picture': '', 'Link': '', 'Brand': 'nike'}, {'Title': 'Ultraboost 21 Shoes', 'Price': 180, 'Currency': ' USD', 'Picture': ',h_280,f_auto,q_auto:sensitive/3728ddf5b7dc4a2ca3e3ac7d0106c5a1_9366/ultraboost-21-shoes.jpg', 'Link': '', 'Brand': 'adidas'}, {'Title': 'Fresh', 'Price': 129, 'Currency': ' USD', 'Picture': '$pdpflexf2$&wid=440&hei=440', 'Link': '', 'Brand': 'newbalance'}, {'Title': 'Jordan Delta Breathe', 'Price': 130, 'Currency': 'USD', 'Picture': '', 'Link': '', 'Brand': 'jordan'},...]

How come the Shoes are not sorted by price here? I have also tried using this code:

myd = mergedCollection.find(myquery)[0]["theAssociatedShoes"].sort("Price")

But that throws a syntax error. I’ve also tried this solution to no avail.

myd = mergedCollection.find(myquery).sort("theAssociatedShoes.Price", -1)

Hello @lilg263,

find() with sort() method can not sort embedded document, you have to use aggregation pipeline, something like,

  • $unwind deconstruct theAssociatedShoes array
  • sort by Price field in descending order
  • $group reconstruct theAssociatedShoes array group by _id
  { $unwind: "$theAssociatedShoes" },
  { $sort: { "theAssociatedShoes.Price": -1 } },
  { $group: { _id: "$_id", theAssociatedShoes: { $push: "$theAssociatedShoes" } } }