2

I've been looking at questions like mongodb: insert if not exists , which gives pointers to "upsert" behavior. However I expect only to create object if certain key is not found, i.e.

if ( $collection->findOne ( array ('key'=>'the_key') ) == NULL ) {
  $collection->insert ( array ('key' => 'the_key', 'content' => 'the_content' );
} else {
  // else don't touch it, so upsert would not fit.
}

I'm using PHP mongodb driver for this. The above code is just the demonstration for my purpose. However there lacks the atomicity required. How this should be achieved?

Thanks in advance!

Community
  • 1
  • 1
Ryan
  • 870
  • 1
  • 7
  • 18

1 Answers1

3

As you should define a unique index for this key anyway, you could also use it to prevent inserting objects with such a key multiple times. Have a look at the index documentation over at:

http://www.mongodb.org/display/DOCS/Indexes#Indexes-UniqueIndexes

Not a nice solution -- imo -- but the only one i can think of, if you do not want to do the update or can not do it for whatever reason. Keep in mind, that you will probably receive an error when trying to insert a object with this same key again, which you would have to handle.

aurora
  • 9,607
  • 7
  • 36
  • 54
  • storing a document with the same index value will alter the document. But, what if I don't want to store a document if some condition is true like "don't store document X if it exists and it's property y=abc " ? – Adelin Oct 29 '12 at 10:13