1

I'm starting with mongoDB and I want to update a nested array in my documents to add some initial value, but I can't find a way to do it with mong.

here is my document :

{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
  {
     "playerName":"Name1"
  },
  {
     "playerName":"Name2"
  }
 ]
}

What I want to do :

{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
  {
     "playerName":"Name1",
     "NewField1":0,
     "NewField2":0
  },
  {
     "playerName":"Name2",
     "NewField1":0,
     "NewField2":0
  }
 ]
}

Does anyone have a solution for this kind of situation?

Community
  • 1
  • 1
Etienne
  • 31
  • 1
  • 3

3 Answers3

3

This adds the new fields to the player array ...

db.collection.update({_id: 'cTZDL7WThChSvsvBT', players: {$exists: true}}, {$set: {'players.$.NewFieldOne': 0, 'players.$.NewFieldTwo': 0}})

... but since Mongo will only update the first element of an array which matches the query you are a bit stuffed. You can, of course, choose which array element to update by using the positional operator (as in my example) or by choosing a specific element (as the previous poster suggested) but until Mongo supports 'array updates' on all elements I think you're left with a solution such as: find the relevant documents and then update each one (i.e. a client side update solution).

glytching
  • 44,936
  • 9
  • 114
  • 120
2

I finally found a way by editing directly the document in JS like this :

  db.doc.find({_id: myDocId}).forEach(function (channel) {
    channel.players.forEach(function (player) {
        player.newField1 = 0;
        player.newField2 = 0;

    });
    db.doc.update({_id: myDocId}, channel);
  });
Etienne
  • 31
  • 1
  • 3
1

considering you want to update an element which is an object also,

how about this?

db.collections.updateOne({_id: "cTZDL7WThChSvsvBT"}, {$set: {"players.0.NewField1": 0, "players.0.NewField2: 0}});
  • Works well but only for the first "player". I don't know the size of the array and I need to add the values to each one. – Etienne Jul 24 '17 at 16:10
  • i think thats similar to this case, https://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb – icyber-ghost Jul 24 '17 at 21:59