kain
kain

Reputation: 5570

Update records with different values in MongoDB

I'm trying to save myself a lot of queries, I'm using Mongoose as ODM.

I have a rather large array topic_codes, say 50k+ elements, I'm doing this (CoffeeScript):

  conditions = code: $in: topic_codes
  update     = $push: samples: date: point_in_time, volume: ??
  options    = multi: true
  TopicArchive.update conditions, update, options, (err) ->

Here I am trying to insert a new subdocument in 'samples', which is an array, of my document with an object with two attributes, date and volume.

While date is the same for every record I'd like to update, volume it's not and can vary from record to record.

Is there a way to achieve my goal without having to go through a huge database hit?

Upvotes: 0

Views: 360

Answers (1)

dcrosta
dcrosta

Reputation: 26258

A multi update updates all matching documents according to the update specifier. If you want to update each document with a different value, then you must issue N updates for N documents (or, more precisely, N updates for each of the N update specifiers you will use). For example, if you have many fewer volumes than topic_codes, you can issue a series of multi-updates, where each update only touches those documents which should have the same volume, using $in as you already are.

Upvotes: 1

Related Questions