How to do a batch upsert from a list of document references?

Viewed 214

I'm doing large updates using an $in query. They look something like this:

collection.update(
    { "ref": { "$in": [<list of ObjectIds>] } }, 
    { "$set": { "foo": "bar" } }, 
    { "multi" : true, "upsert" : false } 
);

This updates any document linked by the ref field and sets the foo field to "bar".

The trouble is that I also want upsert behaviour, such that any missing documents (not already linked by reference) get inserted and linked in the process.

I can achieve this with various long-winded approaches using iteration, but I'm asking if there's a good, succinct and performant way to do it using Mongo operators.

I am running Mongo 2.6 so can't yet use any 3.x features.

Update for clarity:

To give an example of the desired result. Suppose a collection is completely empty and I have two references from another collection:

var refs = [ ObjectId(a), ObjectId(b) ];

I want the upsert to populate two new documents, so the collection will then contain:

[ { "_id": ObjectId(x),
    "ref": ObjectId(a), // <- first ref from $in list
    "foo": "bar"
  },
  { "_id": ObjectId(y),
    "ref": ObjectId(b), // <- second ref from $in list
    "foo": "bar"
  } ]
1 Answers
Related