Database

db={"notifications":[{"user_id":1,"message":"update case - count should be incremented","count":3,"timestamp":ISODate("2024-03-10")},{"user_id":2,"message":"msg doesn't match - should insert","count":5,"timestamp":ISODate("2024-03-10")}]}

Query

db.notifications.aggregate([{"$match":{/** your input user_id and message to upsert here*/"user_id":1,"message":"update case - count should be incremented"}},{"$sort":{"timestamp":-1}},{"$limit":1},{"$set":{"count":{"$add":["$count",1]}}},{"$unionWith":{"coll":"notifications","pipeline":[{"$documents":[/** document to insert if not found*/{"user_id":1,"message":"msg to insert","count":1,"timestamp":"$$NOW"}]}]}},{"$setWindowFields":{"partitionBy":"$user_id","sortBy":{"timestamp":1},"output":{"rank":{"$rank":{}}}}},{"$match":{"rank":1}},{"$unset":"rank"},{"$merge":{"into":"notifications","on":["user_id","message"]}}])

Result