简体   繁体   中英

How to sort data in document

I have a collection with documents.
When I run this code

mydoc = mycol.find({ "orders.lineItems.price": { "$gte": 1.0 } },{ "_id": 0, "orders.lineItems.price": 1 }).sort("orders.lineItems.price").limit(1)

for x in mydoc:
    print(x)

I get this:

{
   'orders':[
      {
         'lineItems':[
            {
               'price':80.38
            },
            {
               'price':2.72
            },
            {
               'price':55.77
            },
            {
               'price':74.9
            }
         ]
      },
      {
         'lineItems':[
            {
               'price':76.01
            },
            {
               'price':5.63
            },
            {
               'price':84.59
            },
            {
               'price':65.29
            }
         ]
      }
   ]
}

As you can see in the code above I tried using sort function
but it did not sort he price

For each 'lineItems' I need:

  • To sort the prices from lowest to highest
  • To sum the prices to a total number.



    Please help me to find a solution.

    Noam.

  • If you could make your list a little more readable and make it a list of list:

    (i assume, your dict is declared 'price_dict')

    def convert_price_dict_to_list(price_dict):
        orders = []
        price_dict = [order['lineItems'] for order in price_dict['orders']]
        for order in price_dict:
            orders.append([item['price'] for item in order])
        return orders
    
    orders = convert_price_dict_to_list(price_dict)
    # [[80.38, 2.72, 55.77, 74.9], [76.01, 5.63, 84.59, 65.29]]
    
    print([sorted(order) for order in orders])
    # [[2.72, 55.77, 74.9, 80.38], [5.63, 65.29, 76.01, 84.59]]
    

    If you really don't want to change to list of lists, you can use the following function to return th dict of lists of dict of lists of dict in your format: (as far i can read it, its correct)

    def sorted_price_dict(price_dict):
        sorted_dict = {'orders': []}
        for order in price_dict['orders']:
            sorted_dict['orders'].append({'lineItems': sorted([price for price in order['lineItems']])})
    
    sorted_price_dict(price_dict)
    # {'orders': [{'lineItems': [{'price': 2.72}, {'price': 55.77}, {'price': 74.9}, {'price': 80.38}]}, {'lineItems': [{'price': 5.63}, {'price': 65.29}, {'price': 76.01}, {'price': 84.59}]}]}
    

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM