'Find MongoDB document based on ID, but replace (or upsert) based on condition

A document with the following format may or may not exist in my collection:

{
  id: 'unique-indicator',
  timestamp: 500,
  value: 100
}

I want to replace this with a new document, if id matches, but also that timestamp is greater than the previous value (500, in this example). Additionally, I want this to work as an upsert, but only based on the id-criteria, NOT the timestamp. For example...

This value should REPLACE (same ID, newer timestamp -> replace):

{
  id: 'unique-indicator',
  timestamp: 1000,
  value: 200
}

This value should DO NOTHING (same ID, older timestamp -> ignore, don't upsert):

{
  id: 'unique-indicator',
  timestamp: 200,
  value: 300
}

This value should UPSERT (new ID -> upsert):

{
  id: 'another-unique-indicator',
  timestamp: 300,
  value: 400
}

Can I achieve this in a single command? My issue e.g. with findOneAndReplace is that it ends as an upsert if ID matches, but timestamp is less. I want this condition to be ignored. I've tried this particular command using the following syntax:

db.myCollection.findOneAndReplace({ 
    id: 'unique-indicator', timestamp: { $lt: 200 } 
  }, 
  {
    id: 'unique-indicator',
    timestamp: 200,
    value: 300
  }, 
  { upsert: true }
)

I'm using a Java driver, but I don't expect language to be particularly relevant.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source