如何从Mongodb文档中获取值?

时间:2017-01-13 03:00:16

标签: mongodb pymongo

我刚开始学习Mongodb和pymongo。我打算将新列表扩展为文档的列表值,我尝试过find()但没有任何结果。以下是我的数据结构:

{ "_id" : ObjectId("58784108b0925e52ec4c478b"), "ip" : "61.228.93.0", "history" : [ { "aging_type" : "static", "from" : "dragonresearchgroup.org", "threat" : "Scanners", "updated_time" : "2016-05-11T20:29:51" } ], "updated_time" : "2017-01-13T10:52:56" }
{ "_id" : ObjectId("58784108b0925e52ec4c478c"), "ip" : "61.231.1.0", "history" : [ { "aging_type" : "static", "from" : "dragonresearchgroup.org", "threat" : "Scanners", "updated_time" : "2016-05-15T15:54:17" } ], "updated_time" : "2017-01-13T10:52:56" }
{ "_id" : ObjectId("58784108b0925e52ec4c478d"), "ip" : "220.135.220.0", "history" : [ { "aging_type" : "static", "from" : "dragonresearchgroup.org", "threat" : "Scanners", "updated_time" : "2016-05-11T08:42:41" } ], "updated_time" : "2017-01-13T10:52:56" }
{ "_id" : ObjectId("58784108b0925e52ec4c478e"), "ip" : "111.248.98.0", "history" : [ { "aging_type" : "static", "from" : "dragonresearchgroup.org", "threat" : "Scanners", "updated_time" : "2016-05-15T06:21:08" } ], "updated_time" : "2017-01-13T10:52:56" }
{ "_id" : ObjectId("58784108b0925e52ec4c478f"), "ip" : "111.243.254.0", "history" : [ { "aging_type" : "static", "from" : "dragonresearchgroup.org", "threat" : "Scanners", "updated_time" : "2016-05-11T00:54:30" } ], "updated_time" : "2017-01-13T10:52:56" }
{ "_id" : ObjectId("58784108b0925e52ec4c4790"), "ip" : "111.248.102.0", "history" : [ { "aging_type" : "static", "from" : "dragonresearchgroup.org", "threat" : "Scanners", "updated_time" : "2016-05-14T04:10:31" } ], "updated_time" : "2017-01-13T10:52:56" }
{ "_id" : ObjectId("58784108b0925e52ec4c4791"), "ip" : "36.229.236.0", "history" : [ { "aging_type" : "static", "from" : "dragonresearchgroup.org", "threat" : "Scanners", "updated_time" : "2016-05-13T22:51:34" } ], "updated_time" : "2017-01-13T10:52:56" }

假设我想要检索"历史"值" ip"值为" 61.228.93.0",然后将[{'aging_type':static,'updated_time':2017-1-13T10:55:22}]扩展到该列表值,然后更新" history"使用扩展列表的值,我该怎么办?   我试过了db.collection.find({"ip":'ip'})['history']db.collection.find({"ip":'ip'},{'history':1}),但似乎没有帮助..   如果有人可以帮我解决这个问题,我将不胜感激

1 个答案:

答案 0 :(得分:1)

通过IP检索文档的历史值:

db.collection.find_one({'ip': '61.228.93.0'})['history']

要添加到历史数组:

result = db.collection.update_one(
    {'ip': '61.228.93.0'},
    {'$push': {'history': {'aging_type': 'static',
                           'updated_time': '2017-1-13T10:55:22'}}})

print(result.raw_result)

打印:

{'updatedExisting': True, u'nModified': 1, u'ok': 1.0, u'n': 1}

要添加到历史数组并使用单个命令获取更新的文档:

from pymongo import ReturnDocument
result = db.collection.find_one_and_update(
    {'ip': '61.228.93.0'},
    {'$push': {'history': {'aging_type': 'static',
                           'updated_time': '2017-1-13T10:55:22'}}},
    return_document=ReturnDocument.AFTER)

print(result)