【问题标题】:Mongo remove document if all elements in array match condition如果数组中的所有元素都匹配条件,Mongo 删除文档
【发布时间】:2020-12-11 04:49:34
【问题描述】:

文档:

{
  _id: 1,
  items: [{thing: 5}, {thing: 7}]
}
{
  _id: 2,
  items: [{thing: 5}, {thing: 11}]
}

如果数组中的所有元素都有“事物”

是否可以通过查询仅查找数组中所有元素都与 $lt 查询匹配的文档?

我试过这个:

db.mycollection.remove({items: {$all: [{$elemMatch: {thing: {$lt: 11}}}]}})

但是,如果数组中的任何元素符合条件,则会删除所有文档。

【问题讨论】:

  • @AlokDeshwal 不是同一个问题。如果数组中的所有元素都匹配,我想删除整个文档,而不仅仅是从文档中提取匹配的元素。

标签: mongodb mongodb-query


【解决方案1】:

使用双重否定(德摩根定律):

{items: {$not: {$elemMatch: {thing: {$gte: 11}}}}}

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2020-05-27
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多