0

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...

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.