0

What is the command to update a mongo collection. I have a variable id and key and the key is newly introduced. I want to update each document in the mongo collection by writing a new variable "key" that has the same value as "id"

So far I have

db.collectionname.update({}, ,{multi:true})

Sorry, I'm new to mongo and would appreciate some good study/reading material

Thanks

Ashh
  • 44,693
  • 14
  • 105
  • 132
Eric chen
  • 31
  • 6
  • 2
    Possible duplicate of [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) – Daniel F Nov 08 '18 at 16:24
  • So it is not possible to do it in one line? I looked at the answers presented and it seems that I have to do a find() to get the whole collection. – Eric chen Nov 08 '18 at 16:54
  • Apparenty it is, via aggregation (for 3.1+). See https://stackoverflow.com/a/37280419/277267 – Daniel F Nov 08 '18 at 16:56
  • 1
    You can do this in one line and it seems to be pretty standard db.collection.find({"updateField":{"$exists":false}}).forEach(function(item){db.collection.update({_id:item._id},{$set:{"updateField":item.currentField}});}); – Eric chen Nov 09 '18 at 14:31
  • AFAIK `find`+`update` first transfers the data to the client, then back to the server. I thought you aimed to getting this done right inside `mongod`, without having to transfer data out and then in again, which is what the aggregation is doing. Aggregation makes the modification right inside `mongod` ("one line") – Daniel F Nov 13 '18 at 15:14

0 Answers0