Pymongo 上查询

问题描述 投票:0回答:1

我需要从集合中的记录中获取两个字段,例如“cpyKey”和“devices”。有多条记录具有相同的“cpyKey”和“设备”。我需要提取记录中可用的最新“run_date”字段的记录,并按“设备”的升序对结果进行排序

使用pymongo。谁能帮我构建查询

agg_result=list(db.xyz.aggregate(
    [#{
        #"$match":{}},
        {"$group":
            {"_id":"$cpyKey","Max Devices":{"$max":"$devices"}}}, #{"$sum":1} -->Gives no. of records related to "_id":"$cpyKey" field
        {"$sort":{"Max Devices":1}}
    ]))

以前我这样做过, 但现在,需要进行更改..我需要从特定 cpyKey 的最新插入记录中获取设备,而不是获取设备的最大值。

我试过了:

mk=list(db.xyz.find({},{"_id":0,"run_date":1}).sort([('run_date',-1)]).limit(1))
print(mk)
#mk is extracting the latest run_date value, but it is associated with a cpyKey
agg_result=list(db.xyz.find({"run_date":mk[0]['run_date']},{"cpyKey":1,"devices":1,"_id":0}))
print(agg_result)
#while implementing mk in above, it gives a record to which it is associated

但它没有给我所有 cpyKey 的值

python mongodb mongodb-query pymongo
1个回答
0
投票

您可以先按

run_date

排序

然后在小组赛中使用

$last
,为每个
Max Devices
检索最后一个元素对应的
cpyKey

[
  {
    "$sort": {
      "run_date": 1
    }
  },
  {
    "$group": {
      "_id": "$cpyKey",
      "Max Devices": {
        "$last": "$Max Devices"
      }
    }
  },
  {
    "$sort": {
      "Max Devices": 1
    }
  }
]

尝试一下这里

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.