0

ai have some mongodb document

horses is array with id, name, type

{
    "_id" : 33333333333,
    "horses" : [ 
        {
            "id" : 72029,
            "name" : "Awol",
            "type" : "flat",
        }, 
        {
            "id" : 822881,
            "name" : "Give Us A Reason",
            "type" : "flat",
        }, 
        {
            "id" : 826474,
            "name" : "Arabian Revolution",
            "type" : "flat",

        }
}

I need to add new fields

I thought something like that, but I did not go to his head

horse = {
   "place" : 1,
   "body"  : 11

}

Card.where({'_id' => 33333333333}).find_and_modify({'$set' => {'horses.' + index.to_s => horse}}, upsert:true)

But all existing fields are removed and inserted new how to do that would be new fields added to existing

  • Does this help : http://stackoverflow.com/questions/10432677/update-field-in-exact-element-array-in-mongodb – Lalit Agarwal Jun 06 '14 at 05:55
  • @LalitAgarwal I read it. Does not help. Still existing object is overwritten completely. And should that be the new fields added to the existing – user3603475 Jun 06 '14 at 05:57
  • Have you considered using update method? - http://docs.mongodb.org/manual/tutorial/modify-documents/#modify-multiple-documents-with-update-method If finds documents matching criteria, and then updates field - if multi is set to true it will update all matching records. – Oto Brglez Jun 06 '14 at 06:08

1 Answers1

2

Indeed, this command will overwrite the subdocument

'$set': {
  'horses.0': {
   "place" : 1,
   "body"  : 11

  }
}

You need to set individual fields:

'$set': {
  'horses.0.place': 1,
  'horses.0.body': 11
}
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367