如何在mongodb中使用facet操作查找字段的不同值
filteredAccording部分和categorizedBy使用我在链接中提供的查询按预期工作,但我在findDistinct部分遇到了问题 在mongodb中,我有以下数据:如何在mongodb中使用facet操作查找字段的不同值,mongodb,mongodb-query,aggregation-framework,aggregation,facet,Mongodb,Mongodb Query,Aggregation Framework,Aggregation,Facet,filteredAccording部分和categorizedBy使用我在链接中提供的查询按预期工作,但我在findDistinct部分遇到了问题 在mongodb中,我有以下数据: { "_id": 10001, "university": "SPYU", "Courses": [ "English", &
{
"_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"
]
}
]
我尝试使用此链接,但没有得到预期的响应。
现在,反应是这样的
"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"
]
}
]
任何帮助都将不胜感激 查询中的快速修复 大学:
,删除$project并仅为标记的$addFields
添加一个操作
解构$unwind
数组dept
by$group
并获取根目录的值数组dept
按null排序,并获取唯一的$group
数组和课程
状态
迭代$reduce
嵌套数组,并使用课程的循环
$setUnion
- 在
字段中设置路线和dest
状态的数组
解构$unwind
数组dest
replace$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" } }
]
}
}
])