UPDATED ANSWER
The updated code you posted is checking for real_ip
and then inserting ip
; so you're not checking the item your actually updating.
My original answer below still stands as the correct approach; however this complete example demonstrates attempting to insert the real_ip
5 times and it shows the value is only inserted once:
from pymongo import MongoClient
collection = MongoClient()['mydatabase'].collection
result = collection.insert_one({'ip': []})
paste_id = result.inserted_id
real_ip = '1.2.3.4'
for i in range(5):
query = {"_id": paste_id, "ip": {"$ne": real_ip}}
collection.update_one(query, {"$push": {"ip": real_ip}})
print(list(collection.find()))
prints:
[{'_id': ObjectId('5feefdb862e2ed3ea952a035'), 'ip': ['1.2.3.4']}]
ORIGINAL ANSWER
Add a check that the IP is not already in the ip
array, e.g.
query = {'ip': {'$ne': ip}}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…