简体   繁体   English

如何删除与 MongoDB $pull 条件不匹配的元素?

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

I have a MongDB document that looks like this:我有一个看起来像这样的 MongDB 文档:

{
   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:我将如何使用 MongoDB $pull 运算符从数组中删除所有不为true元素,有点像这样:

db.myCollection.update({}, {$pull{values:{val:!true}}}, {multi:true})

Use the $elemMatch operator in your query together with the logical operator $ne as follows:在查询中将$elemMatch运算符与逻辑运算符$ne一起使用,如下所示:

db.myCollection.updateMany(
    { "values": { "$elemMatch": { "val": { "$ne": true } } } },
    { "$pull": { "values": { "val": { "$ne": true } } } }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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