簡體   English   中英

如何對文檔中的數據進行排序

[英]How to sort data in document

我有一個文件收集。
當我運行這段代碼

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)

我得到這個:

{
   '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
            }
         ]
      }
   ]
}

如您在上面的代碼中看到的,我嘗試使用排序功能
但這並沒有給他定價

對於每個“ lineItems”,我需要:

  • 從最低到最高的價格排序
  • 將價格總和成一個總數。



    請幫助我找到解決方案。

    諾姆

  • 如果您可以使列表更具可讀性,並使其成為列表列表:

    (我假設您的字典被聲明為“ 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]]
    

    如果您確實不想更改為列表列表,則可以使用以下函數以您的格式返回字典列表的字典:(據我所知,它是正確的)

    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