1

Having user_id="2", how can I set all these hasSeen:false, except for user_id="2" set with hasSeen:true ?

{
    cc: [
          { user_id: "1", hasSeen:true}
         ,{ user_id: "2", hasSeen:false}
         ,{ user_id: "3", hasSeen:false}

    ]
}

I tryed

   .update({ $set:{ 'cc.$.hasSeen':false } })

but it doesn't work...

Sasha Grey
  • 976
  • 1
  • 9
  • 17
  • 1
    Unfortunately the positional operator only works across the first found currently, JIRA again: https://jira.mongodb.org/browse/SERVER-1243 and now searching google I find myself: http://stackoverflow.com/questions/14855246/multiple-use-of-the-positional-operator-to-update-nested-arrays – Sammaye Aug 22 '13 at 14:14

1 Answers1

1

This is not possible in a single operation. You could update each subdocument value. Using getLastError from the update you can determine how many times you have to update eg:

1) Set all hasSeen values to false:

db.test.update( { "cc.hasSeen": true}, 
                { $set: { "cc.$.hasSeen" : false }})
while (db.getLastErrorObj()['n'] > 0) {
    db.test.update( { "cc.hasSeen": true}, 
                    { $set: { "cc.$.hasSeen" : false }})
}

2) Set user_id=2 has seen value to two:

db.test.update( { "cc.user_id": "2"}, 
                { $set: { "cc.$.hasSeen" : true }})

However, this does introduce a race condition as you have n operations instead of a single atomic operation.

Ross
  • 17,861
  • 2
  • 55
  • 73