gpt4 book ai didi

python - 如何将文档附加到mongodb中的现有文档

转载 作者:可可西里 更新时间:2023-11-01 10:41:07 26 4
gpt4 key购买 nike

我编写了一个 python 脚本来解析 Apache 日志并将其按以下格式存储在 mongodb 中:

{
"_id": ObjectId("589e77cf74eea90879f49c80"),
"http_version": "HTTP/1.1",
"time": ISODate("2017-02-11T02:32:46Z"),
"server_ip": "x.x.x.x",
"method": "GET",
"content_length": 529,
"referral": "-",
"uri": "/xxxxxxx.sdsd",
"agent": "Mozilla/5.00 (Nikto/2.1.5) (Evasions:None) (Test:map_codes)",
"status_code": 404
}

我需要找到每个 IP 地址的 404、200 和 302 请求数。我又写了一个脚本来获取值并将其存储在字典中。但是,脚本需要 2 分钟才能获取结果。

db=conn.http_bank
resp= db.http_bank.distinct("server_ip")
total_count=db.http_bank.find().count()
print total_count

def status_code(db,i):

dict_status_code={}
dict_status_code[i]={}
dict_status_code[i].update({'200':db.http_bank.find({"server_ip":i,"status_code":200}).count()})
dict_status_code[i].update({'404':db.http_bank.find({"server_ip":i,"status_code":404}).count()})
dict_status_code[i].update({'302':db.http_bank.find({"server_ip":i,"status_code":302}).count()})

print dict_status_code

print status_code(db,"x.x.x.x")

我需要更改我的 Python 代码逻辑还是应该更改我在 MongoDB 中存储数据的方式?

非常感谢任何帮助。

最佳答案

您可以使用 aggregationstatus_code 进行分组,然后检索一个数组,其中包含每个组 status_code/server_ip 的计数。在 mongoDB shell 中它将是:

db.http_bank.aggregate([{
$group: {
"_id": {
"status_code": "$status_code",
"server_ip": "$server_ip"
},
"count": { "$sum": 1 }
}
}, {
$match: {
"_id.status_code": { "$in": [200, 302, 404] }
}
}])

给出:

{ "_id" : { "status_code" : 404, "server_ip" : "1.1.1.1" }, "count" : 2 }
{ "_id" : { "status_code" : 302, "server_ip" : "3.3.3.3" }, "count" : 2 }
{ "_id" : { "status_code" : 200, "server_ip" : "1.1.1.1" }, "count" : 1 }
{ "_id" : { "status_code" : 302, "server_ip" : "2.2.2.2" }, "count" : 1 }

在 python 中你可以像this那样做:

from pymongo import MongoClient
import datetime

db = MongoClient().testDB

pipeline = [
{
"$match":
{
"time":
{
"$gte": datetime.datetime(2015, 1, 1, 00, 00, 00),
"$lte": datetime.datetime(2018, 1, 1, 00, 00, 00)
}
}
},
{
"$group": {
"_id": {
"status_code": "$status_code",
"server_ip": "$server_ip"
},
"count": {
"$sum": 1
}
}
},
{
"$match": {
"_id.status_code": {
"$in" : [200,302,404]
}
}
}
]

res = list(db.http_bank.aggregate(pipeline))

dict_status_code={}
dict_status_code[1]={}

for i, val in enumerate(res):

data = {
str(int(val["_id"]["status_code"])) : val["count"]
}
key = val["_id"]["server_ip"]
print key, " ==> ", data

给予:

1.1.1.1  ==>  {'404': 2}
3.3.3.3 ==> {'302': 2}
1.1.1.1 ==> {'200': 1}
2.2.2.2 ==> {'302': 1}

关于python - 如何将文档附加到mongodb中的现有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42462698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com