使用Pymongo find仅返回ObjectID和过滤的字段以及错误的结果

时间:2019-09-21 19:21:15

标签: python mongodb pymongo

将Pymongo与find函数一起使用,仅返回ObjectID而不是所有数据。 我的代码:

client = Mongo_Connection()
logs_collection = client[setting['logs-db-name']][setting['logs-collection-name']]
last_time_delta = datetime.datetime.now() - datetime.timedelta(hours=setting['logs-from-X-hours'])

results = logs_collection.find(             # Build the query
                    {'insert_time': {'$gte': last_time_delta}},
                    {rule['field']:rule['value']})

            for log in results:  
                print(log) 

rule ['field'] = logid

rule ['value'] = 4798

我的印刷品显示:

{'_id': ObjectId('5d8672d0f9c301045c071ca3'), 'logid': 1102}
{'_id': ObjectId('5d8672d0f9c301045c071ca4'), 'logid': 5379}
{'_id': ObjectId('5d8672d2f9c301045c071ca5'), 'logid': 5379}
{'_id': ObjectId('5d8672d4f9c301045c071ca6'), 'logid': 4798}

我只想获取logid 4798,并获取所有数据,例如

{
    "_id" : ObjectId("5d8672d4f9c301045c071ca6"),
    "logid" : 4798,
    "client_time" : ISODate("2019-09-22T00:58:27.000Z"),
    "insert_time" : ISODate("2019-09-21T21:58:28.510Z"),
    "type" : 8,
    "src" : "Microsoft-Windows-Security-Auditing",
    "cat" : 13824,
    "dataList" : [ 
        "S-1-5-21-3876502129-1844923064-4112176513-1001", 
        "USER", 
        "PC-DESKTOP", 
        "0xafa8e", 
        "S-1-5-18", 
        "PC-DESKTOP$", 
        "PCNETWORK", 
        "0x3e7", 
        "XboxLive", 
        "1", 
        "1", 
        "%%8099", 
        "0", 
        "2019-09-21T18:58:22.960005000Z", 
        "27652", 
        "S-1-5-21-3876502129-1844923064-4112176513-1001", 
        "USER", 
        "PC-DESKTOP", 
        "0xafac0", 
        "XboxLive", 
        "1", 
        "1", 
        "%%8099", 
        "0", 
        "2019-09-21T18:58:22.960005000Z", 
        "27652", 
        "USER2", 
        "PC-DESKTOP", 
        "S-1-5-21-3876502129-1844923064-4112176513-1004", 
        "S-1-5-21-3876502129-1844923064-4112176513-1001", 
        "USER", 
        "PC-DESKTOP", 
        "0xafa8e", 
        "0x7390", 
        "C:\\Windows\\System32\\mmc.exe"
    ],
    "hostname" : "Pc-Desktop",
    "username" : "User",
    "os" : "Windows",
    "ip_add" : "192.168.0.123",
    "mac_add" : "1c:87:2c:77:f0:99"
}

没有字段和值,我可以从MongoDB获取所有数据,但是必须使用它们从其他服务器的请求中从DB获取动态数据。因此,我尝试查看pymongo教程,未发现任何有关结果。

1 个答案:

答案 0 :(得分:0)

这是一个微妙的选择,但花括号在错误的位置。试试这个:

results = db.logs_collection.find(  # Build the query
    {'insert_time': {'$gte': last_time_delta},
    rule['field']: rule['value']})

获得原始结果的原因是因为您向find函数传递了第二个dict参数。第二个参数是结果过滤器;因此,您不是在过滤记录,而是在过滤结果。

祝您在pymongo旅途中好运!