0

I need to update every record in a collection with a new field.

My documents look something like:

{
  words:['apple','banana','porridge']
} 

and I want to add a new field called word_count that holds the length of the words array (the array length is static).

{
  words:['apple','banana','porridge'],
  word_count : 3
} 

I've tried things along the lines of:

update({}, {$set: {word_count: words.length}}, {multi: true});

And I could do a forEach, however we are talking a fairly large data set of over 2 million rows, so for each is not the most efficient... unless of course it's the only way.

danspants
  • 3,099
  • 3
  • 27
  • 33
  • **If** you can get away with "writing a new collection" then you can do `db.collection.aggregate([{ "$addFields": { "word_count": { "$size" : "$words" } } },{ "$out": "newcollection" }])`. But if you **cannot** then looping is the only way. And you should use `bulkWrite()` just like answers there already say. – Neil Lunn Aug 09 '17 at 23:28
  • You're telling me mongo hasn't changed since 2010 and you still can't refer to the document itself in an update statement? – danspants Aug 09 '17 at 23:29
  • Looks like far more recent answers than 2010 to me. Curb you anger and actually take the time to read and learn please. But no, there is no operation to allow access to an existing document value within an `.update()` statement alone. Should be a JIRA on the answers, but of course that issue is as old as the answers. Looping or new collection is how you do it. – Neil Lunn Aug 09 '17 at 23:30
  • I'm incredulous not angry, surely this is a use case that pops up enough for it to be added as a feature. Ah well, for each it is. – danspants Aug 09 '17 at 23:32
  • Often enough? I suppose so. That might be an indication of the votes on the question and answers from the other people who asked the same thing. And if you took the time to actually read it rather than commenting right away then it should be apparent why. – Neil Lunn Aug 09 '17 at 23:35

0 Answers0