mongodb - $elemMatch 用于过滤 mongodb 中的引用($ref)数组对象不起作用
问题描述
我有 2 个集合 student_details 和 subject_details,每个学生可以有多个科目,我将这些科目存储在 student_details 集合中作为参考数组。
现在我需要获取学生详细信息以及经过过滤的主题,其中 subject_details.status=ACTIVE。
我如何使用对象来实现这$elemMatch
一点$ref
。我正在使用类似下面的东西,但它没有返回任何记录。
db.getCollection('student_details').find( { subjects: { $elemMatch: { $ref: "subject_details", status: 'ACTIVE' }}})
student_details
================
{
"_id" : "STD-1",
"name" : "XYZ",
"subjects" : [
{
"$ref" : "subject_details",
"$id" : "SUB-1"
},
{
"$ref" : "subject_details",
"$id" : "SUB-2"
},
{
"$ref" : "subject_details",
"$id" : "SUB-3"
}
]
}
subject_details
===============
{
"_id" : "SUB-1",
"name" : "MATHEMATICS",
"status" : "ACTIVE"
}
{
"_id" : "SUB-2",
"name" : "PHYSICS",
"status" : "ACTIVE"
}
{
"_id" : "SUB-3",
"name" : "CHEMISTRY",
"status" : "INACTIVE"
}
解决方案
dbref 在查找中使用时很麻烦。但您可以使用以下聚合管道解决它:
db.student_details.aggregate([
{
$unwind: "$subjects"
},
{
$set: {
"fk": {
$arrayElemAt: [{
$objectToArray: "$subjects"
}, 1]
}
}
},
{
$lookup: {
"from": "subject_details",
"localField": "fk.v",
"foreignField": "_id",
"as": "subject"
}
},
{
$match: {
"subject.status": "ACTIVE"
}
},
{
$group: {
"_id": "$_id",
"name": {
$first: "$name"
},
"subjects": {
$push: {
$arrayElemAt: ["$subject", 0]
}
}
}
}
])
生成的对象将是这样的:
{
"_id": "STD-1",
"name": "XYZ",
"subjects": [
{
"_id": "SUB-1",
"name": "MATHEMATICS",
"status": "ACTIVE"
},
{
"_id": "SUB-2",
"name": "PHYSICS",
"status": "ACTIVE"
}
]
}
推荐阅读
- javascript - 将活动类添加到 html 元素不起作用
- reactjs - 如何让 event.preventDefault() 在 React 中工作
- file - $(file < $@) 扩展为空,但不应该
- ansible - 无法将纪元转换为ansible中的可读格式
- extendscript - 循环完成比文件对象读/写/导入快
- windows - 在 Windows KVM 实例中运行 Win10 Docker 容器时出错
- django - 'django.contrib.messages.context_processors.messages' 必须在 DjangoTemplates 中启用
- oracle - TEXT #ORACLE 中的新行
- python - 是否有用于非标准代数类对象的稀疏矩阵运算的 python 库?
- sql - 2个数据集之间的项目结束总数