Steven Filipowicz
Steven Filipowicz

Reputation: 389

MongoDB query insert field into document from a list of Id's

I'm kind of stuck with the following problem. I have a MongoDB filled with documents, of these documents (I have a list with Id's) I need to insert a field.

I have this document:

 {
   "id" : 3639,
   "type" : "P",
   "createdate" : "2011-10-19T11:45:14+0200",
   "name_creator" : "",
   "latitude" : "50.887",
   "longitude" : "9.14999",
   "themes" : [{
       "name" : "Fun",
       "id" : "4"
        }, {
       "name" : "Kids",
       "id" : "5"
   }]
}

I need a query the can insert the themes field into the document, the current themes field does not have to be updates, just 1 new one. I have over 300 Id's where this has to be done.

The document should then look like this: (all the other fields in themes should be removed, just one new one 'Outside')

 {
   "id" : 3639,
   "type" : "P",
   "createdate" : "2011-10-19T11:45:14+0200",
   "name_creator" : "",
   "latitude" : "50.887",
   "longitude" : "9.14999",
   "themes" : [{
       "name" : "Outside",
       "id" : "6"
        }]
}

I would normally write a bit of Java code that would loop over the documents and change them, but I believe (hope) this could be done in a query.

Anyone got an idea on how I could do this?

Thanks for any help!

Upvotes: 0

Views: 181

Answers (1)

Salvador Dali
Salvador Dali

Reputation: 222461

All you need to do is

db.collection.update(
  {id : {$in : [your list of ids]}},
  {$set : {
    theme : [{
       "name" : "Outside",
       "id" : "6"
    }]
  }},
  {multi : true}
)

Upvotes: 1

Related Questions