如何在 MongoDB 聚合中查询数组以获取不同的 AND 和 OR 组合?

How to query an array for different combinations of ANDs and ORs in MongoDB Aggregation?

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

例如,我想要获得完成("Course 1" 和 "Course 2")或 "Course 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)但失败了。

其实$or是顶级运算符,你用错了

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