Priority between $set and $addToSet

Hi guys. Something weird is happening with my API. I use python to make my Android App communicating with MongoDB (Community). I have two collections, one for Data, and one for Metadata. To modify documents in the Metadata collection I use $set. I use $addToSet to add new data to an array in the Data collections. However, I’m noticing some weird behavior.

This is the workflow, which is very trivial. The App sends a JSON with data and metadata, I receive it, I allocate each to two different variables, and then I update each collections with the respective info. Since data comes from the same individual, the ID is the same. So I use (python code):

db.Metadata.update_one({’_id’: username}, {$set: {‘some key’: userMetadata}})
db.Data.update_one({’_id’: username}, {$addToSet: {some other ‘key’: userData}})

Now, the weird thing is that it seems that the first operation cancels out the second. Indeed, I can see changes in the user document in the Metadata collection, but I can’t see changes in the user document in the Data collection. The most weird thing happens when I reverse the order of the operations. so I use:

db.Data.update_one({’_id’: username}, {$addToSet: {some other ‘key’: userData}})
db.Metadata.update_one({’_id’: username}, {$set: {‘some key’: userMetadata}})

In this case, it works perfectly and I see both changes in Metadata and Data collections for the user. I think some priority issue is going on. The problem is that I don’t know which one. And the problem is that I can’t lose user data, especially the ones in Data (Metadata are less important). So even though the reverse order works, I’m still afraid that in some situations (e.g. my server slows down, out of memory issues, other mongo issues) I will lose data due to such a priority issue.

Do you have any idea what is going on here?

Thanks

Hello @Marco_D, welcome to the MongoDB Community forum!

The order in which the two collections are updated do not matter, in terms of priority of $set and $addToSet - there is no such rule. Each write or update operation on a single document is atomic, and there is no way there can be any interference in the two individual update_one operations.

You can include some sample input data, collection documents, and the actual code in your application for a closer look. Also, specify the versions of the MongoDB, Python and PyMongo.

That said, it is possible there is a runtime exception happening on one of the operations and you may want to catch runtime exceptions and deal with them in your application’s code.

1 Like