How to switch a boolean field in an Array element in MongoDB?

Consider this data

{ 
    "_id" : ..., 
    "array" : [
        { "name" : "value1","flag" : true } ,
        { "name" : "value2","flag" : false }
  ]
}

I would like to switch the second element of the array (from false to true)

I know that I can update a specific element using the very useful $ positional operator, for example:

db.myCollection.update(
    {'array.name':'value2'},
    {
        $set: {
            'array.$.flag':true
        }
    },false,true);  

But is there a way to use the $ positional operator also to set the value?

eg. like this?

db.myCollection.update(
    {'array.name':'value2'},
    {
        $set: {
            'array.$.flag':'!array.$.flag' //<--
        }
    },false,true);  
+5
source share
1 answer

No, at the moment this is not possible. MongoDB does not allow expressions in updates that depend on fields in a document. You will need to obtain and install two separate operations.

, (, , ). . false, - true.

// get documents with false flag
db.collection.find({flag: {$mod: [2, 0]}})

// get documents with true flag
db.collection.find({flag: {$mod: [2, 1]}})

// toggle flag
db.collection.update(query, {$inc: {flag: 1}});
+6

All Articles