4

I have a collection of the form

{ id : 1,
  data: [ [ { name : "alice" }, { name : "bob" } ],
          [ { name : "dan" },   { name : "rob" } ] ] }

and the structure of the array has meaning. How would I update the first element ([0][0]) and set name = "alex". I've seen many questions addressing how to update array elements that match a query but not specific elements. To be clear, after the update, the record should look like this:

{ id : 1,
  data: [ [ { name : "alex" },  { name : "bob" } ],
          [ { name : "dan" },   { name : "rob" } ] ] }
0

3 Answers 3

6

Assuming, you have created the structure with some purpose, which ideally becomes tougher to query, you could update it by specifying the index explicitly:

db.collection.update({"id":1},{$set:{"data.0.0.name":"alex"}})
Sign up to request clarification or add additional context in comments.

Comments

1

If we don't have a fixed position and is known at runtime or Dynamic then this approach works perfectly

var setObject = {};
setObject["board."+ x +"."+ y] = player;
gamesColl.update({_id: realId},{
$set:setObject
}, function(err,doc){
console.log(err,doc);
});

Comments

0

you can go further!! if you want to paste indexes as a variable use string template like this

db.collection.update({"id":1},{$set:{[`data.${index}.${index}.name`]:"alex"}})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.