1

I'm trying to increment the capsattribute for every player on a given team in one go.

Each team is structured as below:

{
  name: "Real Madrid",
  players: [ { p_id: "Ronaldo", goal: 135, caps: 134, age: 28 },
             { p_id: "Bale", goal: 75, caps: 45, age: 27 },
             { p_id: "Marcelo", goal: 11, caps: 25, age: 31 },
          { p_id: "Benzema", goal: 125, caps: 95, age: 22 } 
  ]
}

I can only find instructions on how to update one nested record at a time.

db.teams.update({ name: "Real Madrid", "players.p_id" : Ronaldo },
{ $inc : { players.$.caps : 1 });

Can I update all records at once? I can

I will include solution here for others:

var bulk = db.teams.initializeOrderedBulkOp(),   
count = 0;

db.teams.find({ name: "Real Madrid" }).forEach( function(doc) {
var players = doc["players"];

    for( var i = 0; i < players.length; i++) {
        bulk.find(
            {
                "_id": doc._id,
                "players" : { $elemMatch : { "goal" : players[i]["goal"] }}
            }).update({ 
                $inc : { "players.$.goal" : 3 } 
            });
    }

    bulk.execute();
});
Rich131
  • 83
  • 1
  • 6

0 Answers0