[英]Compare current record with MongoDB existing record in Python
i am traversing cvs file line by line using python. 我正在使用python逐行遍历cvs文件。 I need to compare 2 columns of the current record with the existing records in MongoDB.
我需要将当前记录的2列与MongoDB中的现有记录进行比较。 If not present insert it into mongo, else if;
如果不存在,则将其插入mongo,否则; need to compare all the fields of the current record with the existing record in mongoDB and current record would be inserted in the place of old record and only changes in fields would be saved in History json in same document.
需要将当前记录的所有字段与mongoDB中的现有记录进行比较,当前记录将插入旧记录的位置,并且仅字段中的更改将保存在同一文档的History json中。
Existing record in MongoDB: MongoDB中的现有记录:
{
"_id" : ObjectId("59661c4d5e2bb8a9c80e74b8"),
"ID" : 149,
"UID" : "2017-06-01__ccm-401__238AC3E",
"Date" : "2017-06-01",
"Timestamp" : "2017-06-01 08:00:14",
"UCM" : "ccm-401",
"Description" : "SJC08-1-LOBBY",
"Site" : "SJC",
"Building" : "SJC08",
"Floor" : 1,
"Room_Name" : "LOBBY",
"MAC" : "SEP001DA238AC3E"
}
Current record: 当前记录:
{
"ID" : 149,
"UID" : "2017-06-05__ccm-401__238AC3E",
"Date" : "2017-06-01",
"Timestamp" : "2017-06-01 08:00:14",
"UCM" : "ccm-402",
"Description" : "SJC08-1-LOBBY",
"Site" : "SSC",
"Building" : "SJC08",
"Floor" : 1,
"Room_Name" :"LOBBY",
"MAC" : "SEP001DA238AC3E"
}
Here Validation fields are "Description" and "MAC". 此处的验证字段为“描述”和“ MAC”。 If these two fields of the current record is same as existing record in MongoDB, then need to compare other fields of the record.
如果当前记录的这两个字段与MongoDB中的现有记录相同,则需要比较该记录的其他字段。 In this case difference is in ID,UCM,Site field, so need to maintain dictionary of changes like below...
在这种情况下,ID,UCM,Site字段不同,因此需要维护如下的变化字典...
COLL {
'uid':
'mac':
'name':
'ip':
'status':
'date':
.
.
'config_history':
[
{
'date':
'status':
'ip':
.
.
},
{
'date':
'status':
'ip':
.
.
}
]
}
Note: MongoDB is remote access server, so can't do operation like local machine operations 注意:MongoDB是远程访问服务器,因此无法执行本地计算机操作之类的操作
Let's say that you have a CSV with columns separated by ;
假设您有一个CSV,其中各列之间用
;
隔开;
you can compare with mongo documents by this way: 您可以通过以下方式与mongo文档进行比较:
csv_lines = open('myfile.csv', 'r').read().split('\n')
# Iterate over lines
for line in csv_lines:
# Break the line to get the columns
cols = line.split(';')
# Build an object for comparison
csv_dict = {
'UID' : cols[0],
'MAC' : cols[1],
# etc, etc. the key names are equal to the one in Mongo whenever it is possible
}
# compare
cursor = collection.find({
'UID' : csv_dict['UID'],
# etc. with other match criterias
})
# Check if we have documents
if cursor.count():
# Yes, browse the results
for document in cursor:
# Perform deeper comparison by looking all the keys in csv_dict
for key in csv_dict:
# Is key missing in Mongo?
if key not in document:
# Missing key
elif csv_dict[key] != document[key]
# Different value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.