0

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?

Vladimir
  • 2,481
  • 4
  • 31
  • 41
  • Also, read carefully about the multiupdates and just the chapter about the updates itself. It contains lots of notable information. – user Feb 17 '13 at 20:29

1 Answers1

3

The findAndModify command is what you're looking for:

4 . The command returns the original unmodified document selected for this update.

If you were using it in the Mongo shell, your usage would look like:

db.messages.findAndModify({query: {read: false}, update: {read: true}})

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
dirn
  • 19,454
  • 5
  • 69
  • 74
  • I jumped the gun -- this method only allows to modify one document, and return it. I needed something that would do bulk updates/retrieves... – Vladimir Feb 18 '13 at 02:10
  • When you said "I have 1 message" I thought you were working with individual documents. MongoDB doesn't support `findAndModify` for bulk operations. – dirn Feb 18 '13 at 05:33