0

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 uid exists 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

1 Answer 1

2

Use $map to iterate through the array and $cond to conditionally update the array entry with $mergeObject.

db.collection.update({
  _id: {
    $in: [
      "user1",
      "user2"
    ]
  }
},
[
  {
    "$set": {
      "items": {
        "$map": {
          "input": "$items",
          "as": "i",
          "in": {
            "$cond": {
              "if": {
                $eq: [
                  "$$i.uid",
                  "12345"
                ]
              },
              "then": {
                "$mergeObjects": [
                  "$$i",
                  {
                    "uid": "12345",
                    "name": "test"
                  }
                ]
              },
              "else": "$$i"
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.