首页 > 解决方案 > 如何在 MongoDB 聚合中查询数组以获取 AND 和 OR 的不同组合?

问题描述

我正在尝试使用逻辑 AND 和 OR 的不同组合搜索已完成课程的学生列表。

例如,我想让学生完成(“课程 1”和“课程 2”)或“课程 3”

这是我为每个学生提供的数据结构:

{
      "_id" : ObjectId("5c68841cb6b18f31975c8fb0"),
      "courses" :  [ 
           "Course 1", "Course 4"
        ]
}

这是我的代码:

db.getCollection('users').aggregate([
    {
        $match: { 
            "courses": {
                $or: {
                    $all: ["Course 1","Course 2"],
                    $in : ["Course 3"]
                 }
            }
        }
    }
])

我试图嵌套不同的运算符($all, $in, $and, $or)但失败了。

标签: arraysmongodbaggregatelogical-operators

解决方案


实际上$or是顶级操作员,您以错误的方式使用它

db.collection.aggregate([
  { "$match": {
    "$or": [
      { "courses": { "$all": ["Course 1", "Course 2"] }},
      { "courses": { "$in": ["Course 3"] }}
    ]
  }}
])

推荐阅读