Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

PyMongo checking if entry is already in array

I want to have an array of IPs that went to x webpage and have them in an array. However right now everytime an IP connects it gets added, if multiple people connect multiple times there'll be many duplicates.

Currently I'm just using

query = {"_id": paste_id, "ip": {"$ne": real_ip}
collection.update_one(query, {"$push": {"ip": ip}})

but that (logically) just pushes the entry into the array, what'd be a way to check if ip is already in the array?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...