gpt4 book ai didi

mongodb - 如何在 mongodb 中使用 facet 操作查找字段的不同值

转载 作者:行者123 更新时间:2023-12-04 17:21:10 29 4
gpt4 key购买 nike

filteredAccording 部分和 categorizedBy 使用我在链接中提供的查询按预期工作,但我在 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 by dept 并获取根的值数组

查找区别:

  • $group 为 null 并得到唯一的 courses 数组和 status
  • $reduce 迭代 Courses 嵌套数组的循环并使用 $setUnion
  • 获取唯一数组
  • dest字段中制作类(class)和status数组
  • $unwind 解构dest数组
  • $replaceRootdest 对象替换为 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" } }
]
}
}
])

Playground

关于mongodb - 如何在 mongodb 中使用 facet 操作查找字段的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66167965/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com