如何在python3中的MongoDB中查找具有某些条件的最新文档?

时间:2018-08-07 11:08:56

标签: django python-3.x mongodb

我正在用python编写程序,我在mongodb数据库中有一个集合,每个文件包含一个id,一个时间戳,一个ip字符串和一个状态字符串,像这样:

{
  "_id": ObjectId("5b0edbb1094464505f1d2ce3"),
  "id": 20,
  "ip": "172.21.45.225",
  "port": 300,
  "status": "closed",
  "time": ISODate("2018-05-30T17:13:21.308Z")
}

通过即时通讯使用pymongo和djongo插件将Django代码连接到数据库...

我要为每个不同的IP选择状态为“打开”的记录,该记录是该IP的最新记录。 我想出了这种用sql的方法,但是不知道如何在python和mongodb中做到这一点。

sql等效项:

select r1.*
from myRecords r1, myRecords r2
where r1.status = "open" and r1.ip = r2.ip and r1.time > r2.time

1 个答案:

答案 0 :(得分:0)

请看一下我的代码:

db.Testing.aggregate(
    [
        {
            "$match" :
            {   
                "status":"open"  
            }
        }, 
        {
            "$group" :
            {
                "_id": "$ip",  
                "id": { "$first": "$id"},  
                "ip": { "$first": "$ip"},
                "port": { "$first": "$port"},
                "status": { "$first": "$status"},
                "time": { "$max" : "$time"}
            }
        } 

    ]
    )

我的测试记录:

{ "_id" : ObjectId("5b6db06f33f7b2f7cd819d21"), "id" : 20, "ip" : "172.21.45.225", "port" : 300, "status" : "closed", "time" : ISODate("2018-05-30T17:13:21.308Z") }
{ "_id" : ObjectId("5b6db09733f7b2f7cd819d22"), "id" : 20, "ip" : "172.21.45.225", "port" : 300, "status" : "open", "time" : ISODate("2018-04-30T17:13:21.308Z") }
{ "_id" : ObjectId("5b6db09b33f7b2f7cd819d23"), "id" : 20, "ip" : "172.21.45.225", "port" : 300, "status" : "open", "time" : ISODate("2018-03-30T17:13:21.308Z") }
{ "_id" : ObjectId("5b6db09f33f7b2f7cd819d24"), "id" : 20, "ip" : "172.21.45.225", "port" : 300, "status" : "open", "time" : ISODate("2018-03-02T17:13:21.308Z") }
{ "_id" : ObjectId("5b6db3c233f7b2f7cd819d25"), "id" : 20, "ip" : "172.21.44.225", "port" : 300, "status" : "open", "time" : ISODate("2018-03-30T17:13:21.308Z") }
{ "_id" : ObjectId("5b6db3cb33f7b2f7cd819d26"), "id" : 20, "ip" : "172.21.44.225", "port" : 300, "status" : "open", "time" : ISODate("2018-04-30T17:13:21.308Z") }
{ "_id" : ObjectId("5b6db45333f7b2f7cd819d27"), "id" : 20, "ip" : "172.21.45.225", "port" : 300, "status" : "open", "time" : ISODate("2018-06-30T17:13:21.308Z") }

我的结果:

{ "time" : ISODate("2018-04-30T17:13:21.308Z"), "id" : 20, "ip" : "172.21.44.225", "port" : 300, "status" : "open" }
{ "time" : ISODate("2018-06-30T17:13:21.308Z"), "id" : 20, "ip" : "172.21.45.225", "port" : 300, "status" : "open" }