Knowing just the _id
of a document in Mongo is there a straightforward way to write ONE update query to do the following? I think the answer is "no", but I'd like to know about it if there is something that does let this happen.
- Target a document by
_id
(single document). - If the
readAt
field exists on the document, remove it - If the
readAt
field does NOT exist on the document, set it to the current time
Essentially, I want to "toggle" the "read" state (using a Date as a flag) of the document without actually first fetching the document.
Currently I'm using something like:
collection.update(
{_id: notificationDoc._id},
notificationDoc.readAt
? {$unset: {readAt: true}}
: {$set: {readAt: new Date()}}
)
which works fine, but requires I first read in that field. I'm not really worried about race conditions or anything, I'd just prefer to cut out the round trip to the DB.
I've thought of a couple of ways to do it with two update queries in serial with distinct conditions, but that doesn't seem like an improvement.