0

In my upsert request, I'd like to both:

  • update the object in place if it's there, aka

    db.somecollection.update({x: 1}, {$inc: {x: 1}});
    
  • provide a new object if it's not there, aka

    db.somecollection.update({x: 1}, {whole: 0, new: 'yata', object: 42});
    

Is there a way to do that ?

The problem is that upsert seems to work only if you already provide an object in the first place, not a modifier.

edit: I'll be more specific.

I want to update objects of the form

{_id: 12, a: 123, b: 234, c: 345}

my update is just an increment of 1 on one of a, b or c. If the object is not in the base then I'd like to create an object of the form

{_id: 13, a: 1, b: 0, c: 0}

if a was the field I was trying to increment.

Now, if I read the manual correctly, I can write

db.somecollection.update({_id: 12}, {$inc: {a: 1}}, true);

which will work fine to update my a field but which will not create the fields b and c if the object doesn't exist.

m09
  • 7,490
  • 3
  • 31
  • 58

1 Answers1

1

Upserts can work with modifiers; the modifier gets applied to the selector/criteria object when a new document needs to be created. See here. But you do need to set the upsert parameter to true in your update call:

db.somecollection.update({x: 1}, {$inc: {x: 1}}, true);

UPDATE

To get the behavior you're looking for:

db.somecollection.update({_id: 12}, {$inc: {a: 1, b: 0, c: 0}}, true);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • please see my edit. Sorry for not having asked a complete enough question in the first place ;( – m09 Aug 29 '12 at 16:52
  • clever, thanks! Seems limited though. I don't get why instead of a boolean as third argument, an object isn't required, with null if one whishes a normal update. Anyway... – m09 Aug 29 '12 at 17:15