I have the following code for now :
ids = ["user1", "user2"]
item = {"uid": "12345", "name": "test"}
users_collection.update_many({"_id": {"$in": ids}}, {"$pull": {"users": {"uid": item["uid"]}}})
users_collection.update_many({"_id": {"$in": ids}}, {"$addToSet": {"users": item}}, upsert=True)
I am trying to maintain an array users with items with unique uids.
I would like ideally to replace the item if it's already in the array (by uid) to avoid pulling and re adding the item to the array.
To recap :
- Replace the item if
uidexists in the array for one of the item - Add it if the item doesn't exists (knowing it by
uid)
How can i achieve this in one query without aggregation ? Is it even possible ?
PS : Here is more or less what i want :
users_collection.update_many({"_id": {"$in": ids}}, {"$update": {"users": {"$where": {"$exists": "uid"} || {"uid": item["uid"]}, item}}}}, upsert=True)
Thanks in advance