0

I have this user object:

{
     created: 2131092323,
     myClub : {
         balance : 1000,
         fans    : 1000,
         myPlayers : [{
            playerName : 'gogo',
            stamina    : 70   
         },
         {
            playerName : 'gogo8',
            stamina    : 80   
         }]
     }
}

and this query to update:

 users.update(
                { _id : user._id },
                {
                  $set: {
                     'myClub.balance'            : 1000,
                     'myClub.fans'               : 1,
                     'myClub.myPlayers.$.stamina' : 50
                  }
                },
                { upsert : true },
                function(){
                    someCallback()
                }
            );

The inner array named myPlayers is not updating, am i missing something here? Should i had anything in the params of the update statement?

totothegreat
  • 1,633
  • 4
  • 27
  • 59
  • You cannot update more than one matched array element in a single update statement, and in fact my quick search pulls up that basic question answered a couple of times here before. But you also need to understand the positional `$` operator has no use without actually attempting to match an array element in the query. As well as you should never use the positional operator for an array update when also using "upsert". You should be seeing errors that are also lacking from your question, and informative to at least one of those points as well. – Blakes Seven Sep 17 '15 at 09:59
  • So what are my options here? should i split those to two queries? – totothegreat Sep 17 '15 at 10:02
  • Ok just answer this, i know how to update to one of them array element, so what you say is like use bulk operation, fine, but if i have 200 hundred of them objects in array, there will be 200 queries for the same document???? – totothegreat Sep 17 '15 at 10:16
  • @totothegreat this is the only **true** way to do this. – styvane Sep 17 '15 at 10:39
  • 2
    db.user.find().forEach(function (user) { user.myClub.myPlayers.forEach(function (myPlayers) { myPlayers.stamina = 10; }); db.user.save(user); }) – Hitesh Mundra Sep 17 '15 at 11:51
  • @HiteshMundra If you really think that is the answer then you need to read the accepted duplicate link and it's answer and comments to understand how wrong that approach is. How the answer there does it is the only safe and sensible way to approach such an update. – Blakes Seven Sep 17 '15 at 12:29

0 Answers0