2

I have a MongDB document that looks like this:

{
   values: [{val:true}, {val:false}, {val:true}, {val:"dgfdshfsj"}]
}

How would I use the MongoDB $pull operator to remove all elements from the array which are not true, somewhat like this:

db.myCollection.update({}, {$pull{values:{val:!true}}}, {multi:true})
Isaac Krementsov
  • 646
  • 2
  • 12
  • 28

1 Answers1

1

Use the $elemMatch operator in your query together with the logical operator $ne as follows:

db.myCollection.updateMany(
    { "values": { "$elemMatch": { "val": { "$ne": true } } } },
    { "$pull": { "values": { "val": { "$ne": true } } } }
)
chridam
  • 100,957
  • 23
  • 236
  • 235