简体   繁体   English

如何对文档中的数据进行排序

[英]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: 对于每个“ lineItems”,我需要:

  • 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') (我假设您的字典被声明为“ 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}]}]}
    

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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