【问题标题】:i have 2 regions , in 2 regions there are 2 cities. i have to output the count and name of cities. how can i get it我有 2 个地区,在 2 个地区有 2 个城市。我必须输出城市的数量和名称。我怎么才能得到它
【发布时间】:2022-01-15 23:57:43
【问题描述】:

{'_id': ObjectId('619f4e58b1a936e640635e97'), 'OrderDate': '01-01-2020', 'Region': 'East', 'City': 'Boston', 'Category': 'Bars' , 'Product': 'Carrot', 'Quantity': '33', 'UnitPrice': '1.77', 'TotalPrice': 58.0, '': 'Sum of TotalPrice'}

{'_id': ObjectId('619f4e58b1a936e640635e98'), 'OrderDate': '04-01-2020', 'Region': 'East', 'City': 'Boston', 'Category': 'Crackers' , 'Product': 'Whole Wheat', 'Quantity': '87', 'UnitPrice': '3.49', 'TotalPrice': 303.0, '': '17988.66'}

{'_id': ObjectId('619f4e58b1a936e640635e99'), 'OrderDate': '07-01-2020', 'Region': 'West', 'City': 'Los Angeles', 'Category': 'Cookies ','产品':'巧克力片','数量':'58','单价':'1.87','TotalPrice':108.46,'':'15336.92'}

{'_id': ObjectId('619f4e58b1a936e640635e9a'), 'OrderDate': '10-01-2020', 'Region': 'East', 'City': 'New York', 'Category': 'Cookies ','产品':'巧克力片','数量':'82','单价':'1.87','TotalPrice':153.34,'':'33325.58'}

{'_id': ObjectId('619f4e58b1a936e640635e9b'), 'OrderDate': '13-01-2020', 'Region': 'East', 'City': 'Boston', 'Category': 'Cookies' , '产品': 'Arrowroot', '数量': '38', '单价': '2.18', 'TotalPrice': 82.84}

{'_id': ObjectId('619f4e58b1a936e640635e9c'), 'OrderDate': '16-01-2020', 'Region': 'East', 'City': 'Boston', 'Category': 'Bars' ,“产品”:“胡萝卜”,“数量”:“54”,“单价”:“1.77”,“总价”:95.58}

{'_id': ObjectId('619f4e58b1a936e640635e9d'), 'OrderDate': '19-01-2020', 'Region': 'East', 'City': 'Boston', 'Category': 'Crackers' ,“产品”:“全麦”,“数量”:“149”,“单价”:“3.49”,“总价”:520.01}

{'_id': ObjectId('619f4e58b1a936e640635e9e'), 'OrderDate': '22-01-2020', 'Region': 'West', 'City': 'Los Angeles', 'Category': '酒吧','产品':'胡萝卜','数量':'51','单价':'1.77','TotalPrice':90.27}

w=db.sales.count_documents({"Region":"West"})
e=db.sales.count_documents({"Region":"East"})
print("Total count of orders in East region and West region are",w,"and",e)
a=db.sales.aggregate([{"$project":{"Region":1,"City":1}}])
for i in a:
print(i)

【问题讨论】:

    标签: pymongo


    【解决方案1】:

    试试这个,参考https://mongoplayground.net/p/d4L-QQXh1Id

     db.collection.aggregate([
      {
        "$group": {
          "_id": {
            "Region": "$Region",
            "City": "$City"
          },
          "Total Amount": {
            "$sum": "$TotalPrice"
          },
          "count": {
            "$sum": 1
          }
        },
        
      },
      {
        "$project": {
          "_id": 0,
          "Cities": "$_id.City",
          "Total Count": "$count",
          "Total Amount": "$Total Amount"
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-08
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      相关资源
      最近更新 更多