【问题标题】:mongodb - Filter object where all elements from nested array match the conditionmongodb - 过滤对象,其中嵌套数组中的所有元素都符合条件
【发布时间】:2018-03-05 00:27:04
【问题描述】:

假设一个数据库包含类似的东西

{  
   "grades":[  
      {  
         "grade":"A",
         "score":2
      },
      {  
         "grade":"A",
         "score":6
      },

   ],
   "name":"Morris Park Bake Shop"
},
{  
   "grades":[  
      {  
         "grade":"A",
         "score":8
      },
      {  
         "grade":"B",
         "score":23
      }
   ],
   "name":"Wendy'S"
}

如何应用过滤器,只返回所有等级为“A”的餐厅?

如果我尝试 db.restaurants.find({ "grades.grade" : "A" } ),它的工作方式是在我的元素中搜索任何等级。

我尝试使用带有 unwind to 的聚合,但它做同样的事情,它打开成绩、过滤并返回任何匹配的餐厅...

【问题讨论】:

标签: mongodb


【解决方案1】:

在你的情况下,我会这样做:

db.getCollection('test').aggregate([
{$unwind:"$grades"},
    { $group: { 
        _id: '$_id', 
        grades : { $first: '$grades' },  
        all_grades: { $sum: 1 },
        all_grades_that_match: { $sum: { $cond: [ { $eq: [ '$grades.grade', "A" ] }, 1, 0 ] } },     
        name: { $first: '$name' }     
    }},
   { $project: {
        _id: 1,
        name: 1,
        grades: 1,
        arrays_equal: { $cond: [ { $eq: [ '$all_grades', '$all_grades_that_match' ] }, 1, 0 ] }
    }},
    { $match: { 'arrays_equal' : 1 } } 
])

分组操作会统计总成绩和你查询的匹配成绩的数量,投影会比较这两个结果是否相等,最后,匹配操作只会保留arrays_equal为的那些真的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2020-09-24
    相关资源
    最近更新 更多