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?

0

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your solution, works! And thanks also for the background explanation.
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);
  });

Comments

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}});

2 Comments

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.
i think thats similar to this case, stackoverflow.com/questions/4669178/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.