0

I currently have a mongo object set up like so.

{
        "_id" : "FtFKS23swBSEtEJAK",
        "active_users" : [
                {
                        "user" : {
                                "profile" : {
                                        ...
                                }
                        },
                        "maxMessages" : 25
                },
                {
                        "user" : {
                                "profile" : {
                                        ...
                                }
                        }
                        "maxMessages" : 25
                }
        ],
        "display_name" : "Testing"
}

Now, I am trying to run a mongo query that will go through the embedded active users and increment the maxMessages by a given value.

I cant seem to get it right though.

This is my failed attempt

activeUsersLength = Rooms.findOne({}).active_users.length

for i in [0..activeUsersLength-1]
    Rooms.update({_id: room}, {$inc: {'active_users.' + i + '.maxMessages': 1}})
Scalahansolo
  • 2,615
  • 6
  • 26
  • 43
  • possible duplicate of [how to update multiple array elements in mongodb](http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb) – dgiugg Aug 01 '14 at 17:12

1 Answers1

0
Rooms.update({_id:room, "active_users.user": { $exists : true } },{$inc:{"active_users.$.maxMessages":1}  })

I have not tested

Take a look http://docs.mongodb.org/manual/reference/operator/projection/positional/#proj.S

You can t update more element in Array https://jira.mongodb.org/browse/SERVER-1243 thanks to @dgiugg's comment

Barno
  • 3,271
  • 5
  • 28
  • 58
  • I tried this earlier. The error that is throw is `Exception while invoking method 'insertMsg' MongoError: Cannot apply the positional operator without a corresponding query field containing an array.` – Scalahansolo Aug 01 '14 at 16:54
  • @SeanCallahan i have updated, can you try? when i can test it on my cpu – Barno Aug 01 '14 at 17:06
  • 1
    It won't work: http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb, see also https://jira.mongodb.org/browse/SERVER-1243. It will update only the first element of the array. – dgiugg Aug 01 '14 at 17:08