0
obj = {
  date: 137097408891,
  id: '1234',
  value: 'value'
}

What I want to do it apply the value field to the object with the id, only if the date is newer then the current one saved. If no document with that ID is saved, just save this one.

I'm using node-mongodb-native. Is there a way to do this without first getting the document checking the date and saving it again?

Thanks

boom
  • 10,856
  • 9
  • 43
  • 64

1 Answers1

1

Given object o

db.collection.update( { id:o.id, date: { $lt:o.date } }, {$set : { o }}, {upsert:true} );

This is assuming there is a unique index on id.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
  • 1
    Ah, ok, I was thinking this but I thought it would try to insert a new document if the saved one was newer. – boom Jun 11 '13 at 18:47
  • it will, but it will fail since unique constraint on id will be violated which is what you want :) – Asya Kamsky Jun 11 '13 at 19:07
  • why does this throw, `Error: Cannot use a writeConcern without a provided callback`? – boom Jun 11 '13 at 19:11
  • it calls back the err for inserting the same id, should i just disregard it? – boom Jun 11 '13 at 19:13
  • 1
    exactly. you might want to verify the type of error - since you don't want to inadvertently disregard a different error from the same operation... – Asya Kamsky Jun 11 '13 at 19:23