簡體   English   中英

如何使用python和pymongo制作二維結構(詞典中的詞典)以存儲在MongoDB中?

[英]How can I make a two dimensional structure(dictionary inside a dictionary) using python and pymongo to store in MongoDB?

我會經常低於數據

item_1 = { "ip" : "66.70.175.192", "domain" : null, "date_downloaded" : "2017:08:23 12:25:05", "scanned_date_with_port" : [ { "scanned_date" : "2017:08:22 04:00:03", "port" : 25 }, { "scanned_date" : "2017:08:22 04:00:03", "port" : 110 } ], "ports" : [ 25, 110 ] }

如何通過以下結構將數據保存到pymongo中:

{"ip_1" : {"port" : [scanned_date_1, scanned_date_2]}, {"port_2" : [scanned_date_1, scanned_date_2]  }, "domain_name" : ["domain"] }
{"ip_2" : {"port" : [scanned_date_1, scanned_date_2]}, {"port_2" : [scanned_date_1, scanned_date_2]  }, "domain_name" : ["domain"] }

每當有新IP出現時,如果已經存在需要添加,否則添加新IP。 如果端口已經在一個Ip中,則在端口上附加scand_date,否則添加該端口和scand_date。

我如何有效地做到這一點? 將有大量數據要循環。

for item in all_items:

每個“項目”將具有上述item_1的結構。

您可以做的就是更改數據結構,並統一方式,即只要求給定IP和端口即可獲得數據庫中新IP和IP的方式,就可以得到部分填充或填充的結構。如果為空,您將始終將新數據附加到現有列表或空列表中。 您將為此而設工廠。

使用$ push更新運算符可以追加到數組。 這是一個完整的示例:

client = MongoClient()
db = client.test

collection = db.collection
collection.delete_many({})
collection.insert_many([
    {"_id": "ip_1", "port": [1, 2], "port_2": [1, 2], "domain_name": "domain"},
    {"_id": "ip_2", "port": [1, 2], "port_2": [1, 2], "domain_name": "domain"},
])

# A new request comes in with address "ip_2", port "port_2", timestamp "3".
collection.update_one({
    "_id": "ip_2",
}, {
    "$push": {"port_2": 3}
})

import pprint
pprint.pprint(collection.find_one("ip_2"))

終於我得到了解決方案。

        bulkop = self.coll_historical_data.initialize_ordered_bulk_op()

        for rs in resultset:
            ip = rs["ip"]
            scanned_date_with_port = rs["scanned_date_with_port"]
            domain = rs["domain"]
            for data in scanned_date_with_port:
                scanned_date = data["scanned_date"]
                port = data["port"]
                # insert if not found, else update
                retval = bulkop.find({"ip" : ip}).upsert().update({"$push" : {str(port) : scanned_date }, "$addToSet" : {"domain" : domain}} )

        retval = bulkop.execute()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM