I have a collection called “messages”. Each message has a ‘read’ boolean value. In some instances when I retrieve the messages, I’d like to set the value to ‘true’, while returning the pre-modified value.
So, let’s say I have 1 message, whose ‘read’ value is ‘false’. When I retrieve it, I’d like to return the initial ‘false’ value, but in the same operation I’d like to set it to ‘true’.
Any way of doing that?
The
findAndModifycommand is what you’re looking for:If you were using it in the Mongo shell, your usage would look like:
It looks like you’re using Java, though. The Java driver offers a few different signatures for
findAndModify(). You can check them out in the javadoc for DBCollection.