arrays - 如何在 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
)但失败了。
解决方案
实际上$or
是顶级操作员,您以错误的方式使用它
db.collection.aggregate([
{ "$match": {
"$or": [
{ "courses": { "$all": ["Course 1", "Course 2"] }},
{ "courses": { "$in": ["Course 3"] }}
]
}}
])
推荐阅读
- php - 如何将 ID 从 url 传递到 laravel 中的控制器
- android - 在 Android Studio 中修改计算器
- javascript - 如何在节点js中以JSON解析对象中的函数
- java - 如何使用 poi 将 jtable 保存到 excel 中,包括标题?
- python - 跟踪 BFS 中的节点 - Python、迷宫
- r - 为 R 安装 qiimer 包时出错
- javascript - 身份验证 POST 适用于“请求”但不适用于“节点获取”
- excel - 是否可以立即从表单更新 Excel 单元格,而不需要按下更新按钮?
- java - 如何在休眠中的多对多映射中加入中间表
- javascript - Angular 项目没有运行