database - MongoDB - 从数组中的所有匹配对象中获取一个字段?
问题描述
我一直在将 mySQL 迁移到 mongoDB。我想嵌入教师,课程表到教师表。我有一个 mongo 数据库结构如下。
{
"_id" : "14365",
"ID" : "14365",
"name" : "Lembr",
"dept_name" : "Accounting",
"salary" : 32241.56,
"teaches" : [
{
"ID" : "14365",
"course_id" : "200",
"sec_id" : "1",
"semester" : "Spring",
"year" : 2007.0,
"course" : {
"course_id" : "200",
"title" : "The Music of the Ramones",
"dept_name" : "Accounting",
"credits" : 4.0
}
},
{
"ID" : "14365",
"course_id" : "843",
"sec_id" : "1",
"semester" : "Fall",
"year" : 2010.0,
"course" : {
"course_id" : "843",
"title" : "Environmental Law",
"dept_name" : "Math",
"credits" : 4.0
}
}
]
}
我想像下面的 SQL 查询一样查询。
SELECT name, title From instructor Natural join teaches Natural join course;
如何在 mongodb 中查询?
解决方案
您需要 MongoDB 的聚合运算符$reduce:
db.collection.aggregate([
/** Using project stage we'll project only needed fields */
{
$project: {
_id: 0, // _id is by default included - you need to exclude it
name: 1,
title: {
$reduce: {
input: "$teaches", // Iterate on objects of `teaches` array
initialValue: [], // Initial value
in: {
$cond: [
{ $eq: ["$$this.course.dept_name", "$dept_name"] }, // condition to check
{
$concatArrays: ["$$value", ["$$this.course.title"]], // If condition is met push values to array
},
"$$value" // If not send same holding array back for this iteration
]
}
}
}
}
}
]);
测试: mongoplayground
测试: $filter
: mongoplayground
笔记 :
我们曾经$reduce
将数组中不同对象的所有标题teaches
带到一个数组中。您也可以使用$filter来实现类似的事情。如果在任何情况下,如果您title
只是数组中的一个元素(数组中没有重复元素dept_name
) ,teaches
那么您可以使用$unwind或$arrayElemAt将title
数组转换为字符串。
推荐阅读
- c++ - 对于超出代码中指定范围的值,对角差分算法的输入不正确
- java - @NotNull 注解不适用于 Double
- parseint - 如何在 Main 中调用 parseInt 方法?
- ionic-framework - Ionic-2-Calendar 月查看事件详细信息模板 - 我如何访问有关非时间事件的任何信息?
- python - 使用 win32print 在 Python 中将一行文本发送到 ESC/POS 打印机
- java - Selenium find elements using xpath and limiting the search based on a parent class
- kotlin - 如何配置 build.gradle.kts 以修复错误“Duplicate JVM class name generated from: package-fragment”
- angular - 错误类型错误:当我尝试在 ngOnInit() 中修补值时,无法读取未定义的属性“形式”
- javascript - 如何使用 Hapi/bell 登录 Twitter 用户?
- matlab - 使不同的子图在matlab上具有相同的颜色范围