Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在MongoDB中查找数组中具有max和min值的文档_Python_Mongodb - Fatal编程技术网

Python 如何在MongoDB中查找数组中具有max和min值的文档

Python 如何在MongoDB中查找数组中具有max和min值的文档,python,mongodb,Python,Mongodb,我已经为此挣扎了一段时间。我有州和度假屋的数据。我需要找到每种度假屋的数量,并返回位置最多和最少的房产类型。我已经能够按状态分组并计算数组中的属性数。我只需要拿出最多和最少的财产 我掌握的数据 {'_id': 'CA', 'properties': [{'property_type': 'Camper/RV', 'quantity': 1}, {'property_type': 'Hostel', 'quantity': 2}, ...]} {'_id': 'BR', 'properties':

我已经为此挣扎了一段时间。我有州和度假屋的数据。我需要找到每种度假屋的数量,并返回位置最多和最少的房产类型。我已经能够按状态分组并计算数组中的属性数。我只需要拿出最多和最少的财产

我掌握的数据

{'_id': 'CA', 'properties': [{'property_type': 'Camper/RV', 'quantity': 1}, {'property_type': 'Hostel', 'quantity': 2}, ...]}
{'_id': 'BR', 'properties': [{'property_type': 'Guest suite', 'quantity': 3}, {'property_type': 'Bed and breakfast', 'quantity': 7}, ...]}
...
我想写一个查询,返回如下数据

{'_id': 'TR', 'most_type': 'Apartment', 'most_number': 53, 'least_type': 'Camper/RV', 'least_number': 5}
{'_id': 'CA', 'most_type': 'House', 'most_number': 53, 'least_type': 'TinyHouse', 'least_number': 3}
...
你用一个

试试看

db.collection.aggregate([
  {
    "$unwind": "$properties"
  },
  {
    "$sort": {
      "properties.quantity": -1
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "most_type": {
        "$first": "$properties.property_type"
      },
      "most_number": {
        "$first": "$properties.quantity"
      },
      "least_type": {
        "$last": "$properties.property_type"
      },
      "least_number": {
        "$last": "$properties.quantity"
      }
    }
  }
])