How do I use $cond to make a condition for entire document, not just one field?

I’m trying to make a query where it checks if a document exists based on filter, if it does, it checks if the timestamp is newer and updates if that is the case, and if the document doesn’t exist, it creates one. The old code that was supposed to do this was as follows:

	{"item_number": item_data["item_number"], "component_id": item_data["component_id"], "timestamp": {"$lte": item_data["timestamp"]}},
	{"$set": item_data},

This however caused a data duplication bug if the timestamp of the uploaded file was older than the one existing in the collection (because it no longer matched the filter). I also tried to do this:

	{"item_number": item_data["item_number"], "component_id": item_data["component_id"]},
	{"$set": {
		"item_number": {"$cond": [{"timestamp": {"$lte": item_data["timestamp"]}}, item_data["item_number"], "$item_number"]},
		"item_name": {"$cond": [{"timestamp": {"$lte": item_data["timestamp"]}}, item_data["item_name"], "$item_name"]},
		"component_id": {"$cond": [{"timestamp": {"$lte": item_data["timestamp"]}}, item_data["component_id"], "$component_id"]},
		"component_name": {"$cond": [{"timestamp": {"$lte": item_data["timestamp"]}}, item_data["component_name"], "$component_name"]},

Which is a bit of a mess (because the actual query has more fields than what I included) and it caused some documents getting deleted for some reason. Is there a better way of doing this? This sounds like something that should be possible, but I can’t figure out how to do it.

To help us experiment with your use-cases please share sample documents and sample item_data values for each situations.

The data that we are working with is sensitive, so I can’t share it. In a bigger picture the contents of collection and documents don’t actually matter, besides the timestamp and how you decide to identify which document to update. The concept here is more important than the details, like what the data looks like, etc.