简体   繁体   中英

How do I remove elements not matching conditions with MongoDB $pull?

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})

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 } } } }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM