0

How do I create a document with an ID only if it doesn't exist, atomically? If it already exists, I would like it to callback (with the knowledge that it exists) and delete that document.

A naive find and check on the application layer seems to have room for failure.

Ex: I have a document

{_id: "Alice"}

If the document is already in the collection then delete the document. If the document is not in the collection then insert into the collection.

Harry
  • 52,711
  • 71
  • 177
  • 261
  • What do you mean by *"delete itself"*? Can you be more specific about the example? Or do you actually just really mean "replacing" the matched content with the new content? Pretty sure you really just mean the common case without any other specific example – Neil Lunn Nov 12 '18 at 04:32
  • @NeilLunn I mean delete the document, sorry. I added an example, hope that clarifies it. – Harry Nov 12 '18 at 04:36
  • You "added" a **single** line. You're being asked to provide a fair bit more detail than that. I would still strongly suggest what you are actually looking for is already answered and that you spend your time looking at that "first". If you still think it does not after reading, then your "detailed" question might have other consideration for a different answer. – Neil Lunn Nov 12 '18 at 04:38
  • @NeilLunn What I'm asking is very simple so that's why it's short. Your suggested question is an upsert, it doesn't return knowledge of whether or not the document already exists. "If it already exists, I would like it to callback (with the knowledge that it exists) and delete that document." I honestly don't understand what else to say without repeating myself. I would love to write more to expound on the issue but honestly have no idea. – Harry Nov 12 '18 at 04:42

0 Answers0