mongodb - 如何在 mongodb 中使用 facet 操作查找字段的不同值
问题描述
使用我在链接中提供的查询,filteredAccording 部分和分类依据按预期工作,但我在 findDistinct 部分遇到问题。
在 mongodb 我有以下数据:
{
"_id": 10001,
"university": "SPYU",
"Courses": [
"English",
"French"
],
"dept": [
"Literature"
],
"type": [
"Autonomous"
],
"status": "ACTIVE",
"isMarked": true
},
{
"_id": 10002,
"university": "SPYU",
"Courses": [
"English",
"French"
],
"dept": [
"Literature"
],
"type": [
"Autonomous"
],
"status": "NON-ACTIVE",
"isMarked": true
}
我希望得到的回应是:
"university": [
{
"name": "Literature",
"values": [
{
"_id": 10001,
"university": "SPYU",
"Courses": [
"English",
"French"
],
"dept": [
"Literature"
],
"type": [
"Autonomous"
],
"status": "ACTIVE",
"isMarked": true
},
{
"_id": 10002,
"university": "SPYU",
"Courses": [
"English",
"French"
],
"dept": [
"Literature"
],
"type": [
"Autonomous"
],
"status": "NON-ACTIVE",
"isMarked": true
}
]
}
],
"findDistinct": [
{
"name": "Courses",
"values": [
"English",
"French"
]
},
{
"name": "Status",
"values": [
"ACTIVE",
"NON-ACTIVE"
]
}
]
我使用此链接进行了尝试,但响应未按预期进行。 https://mongoplayground.net/p/XECZvRMmt3T
现在,回应是这样的
"universities": [
{
"name": "Literature",
"values": [
{
"_id": 10001,
"university": "SPYU",
"Courses": [
"English",
"French"
],
"dept": [
"Literature"
],
"type": [
"Autonomous"
],
"status": "ACTIVE",
"isMarked": true
},
{
"_id": 10002,
"university": "SPYU",
"Courses": [
"English",
"French"
],
"dept": [
"Literature"
],
"type": [
"Autonomous"
],
"status": "NON-ACTIVE",
"isMarked": true
}
]
}
],
"findDistinct": [
{
"Courses": [
"English",
"French"
]
},
{
"status": [
"ACTIVE",
"NON-ACTIVE"
]
}
]
任何帮助将不胜感激!!
解决方案
快速修复您的查询,
大学:
$addFields
, 删除 $project 并仅添加一项操作isMarked
$unwind
解构dept
数组$group
通过dept
并获取根的值数组
发现区别:
$group
通过 null 并获得唯一的courses
数组和status
$reduce
Courses
迭代嵌套数组的循环并使用获取唯一数组$setUnion
status
制作课程和dest
现场数组$unwind
解构dest
数组$replaceRoot
将dest
对象替换为根
db.collection.aggregate([
{ $match: { university: "SPYU" }
},
{
$facet: {
universities: [
{ $addFields: { isMarked: { $in: ["French", "$Courses"] } } },
{ $unwind: "$dept" },
{
$group: {
_id: "$dept",
values: { $push: "$$ROOT" }
}
}
],
findDistinct: [
{
$group: {
_id: null,
Courses: { $addToSet: "$Courses" },
Status: { $addToSet: "$status" }
}
},
{
$project: {
_id: 0,
dist: [
{
name: "Courses",
values: {
$reduce: {
input: "$Courses",
initialValue: [],
in: { $setUnion: ["$$this", "$$value"] }
}
}
},
{
name: "Status",
values: "$Status"
}
]
}
},
{ $unwind: "$dist" },
{ $replaceRoot: { newRoot: "$dist" } }
]
}
}
])
推荐阅读
- python - Pandas:从一个数据框列中过滤数据并更新另一个 df 列
- amazon-web-services - 写入 S3 的 Lambda 函数 - 访问 S3 的 IAM 策略
- reactjs - 如何在 react 中使用 chart.js 映射多个图表
- laravel - 如果数据库上的 id 重复,则返回 flash 消息
- javascript - Mixitup 库 - 不要对非目标元素运行排序
- angular - Angular/typescript,变量的一些问题
- asp.net - 带有 EF Core 的 DDD(DTO、业务等)
- html - 视频不会在 Chrome 和 Firefox 上自动播放
- dataset - 无法在 Jupyter Notebook 中导入数据集
- python - 从从json导入的对象列表(dict)中获取字段列表