首页 > 解决方案 > 查询以在对象数组中的所有对象都匹配时返回结果

问题描述

我的文档结构如下所示:

users : [
  {_id:1,
  'name': 'xxxxx',
  'children':[
    {age:13, weight: 80 lbs},
    {age: 12, weight: 65 lbs}
  ]
  }
  {_id:2,
  'name': 'yyyyy',
  'children':[
    {age:11, weight: 65 lbs},
    {age: 9, weight: 55 lbs}
  ]
  }
]

我正在尝试获取子数组中所有元素都小于 12 岁的对象。所以预期的输出看起来像:

[
  {_id:2,
      'name': 'yyyyy',
      'children':[
        {age:11, weight: 65 lbs},
        {age: 9, weight: 55 lbs}
      ]
      }
]

我尝试了 elem match 但它只查找数组中的任何匹配项。我正在寻找所有的比赛。我试过这个,但没有用。

{"children":{"$all":[{"$elemMatch":{"age":{"$lte":12}}}]}}

标签: mongodb

解决方案


db.collection.aggregate([
  { 
      $match: { 
          $expr: { 
              $eq: [ { $reduce: { input: "$children", 
                                  initialValue: true, 
                                  in: { $cond: [ { $gte: [ "$$this.age", 12 ] }, "$$value", false ] }
                     } },                   
                     true 
              ] 
          } 
      } 
  }
])

聚合使用$reduce数组运算符检查children数组中的所有元素是否age大于或等于 12。归约操作返回布尔值truefalse(仅当所有数组元素都匹配时才为真)。$match阶段过滤带有结果的文档true


推荐阅读