问题描述
filteredAccording 部分和categorizedBy 使用我在链接中提供的查询按预期工作,但我在finddistinct 部分遇到了问题。
在mongodb中我有以下数据:
{
"_id": 10001,"university": "SPYU","Courses": [
"English","french"
],"dept": [
"Literature"
],"type": [
"Autonomous"
],"status": "ACTIVE","isMarked": true
},{
"_id": 10002,"status": "NON-ACTIVE","isMarked": true
}
我希望得到的回应是:
"university": [
{
"name": "Literature","values": [
{
"_id": 10001,"isMarked": true
}
]
}
],"finddistinct": [
{
"name": "Courses","values": [
"English","french"
]
},{
"name": "Status","values": [
"ACTIVE","NON-ACTIVE"
]
}
]
我使用此链接进行了尝试,但没有按预期响应。 https://mongoplayground.net/p/XECZvRMmt3T
现在,响应是这样的
"universities": [
{
"name": "Literature","finddistinct": [
{
"Courses": [
"English",{
"status": [
"ACTIVE","NON-ACTIVE"
]
}
]
任何帮助将不胜感激!
解决方法
快速修复您的查询,
大学:
-
$addFields
,删除 $project 并只为isMarked
添加一个操作 -
$unwind
解构dept
数组 -
$group
bydept
并获取根值数组
findDistinct:
-
$group
by null 并获得唯一的courses
数组和status
-
$reduce
迭代Courses
嵌套数组的循环并使用$setUnion
获取唯一数组
- 在
status
字段中创建数组和dest
-
$unwind
解构dest
数组 -
$replaceRoot
将dest
对象替换为 root
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" } }
]
}
}
])