英文:
MongoDb aggregation for filtering list based on ids and mapping this filtered list to another field
问题
以下是您提供的内容的翻译结果:
在我的 MongoDB 中,数据如下所示:
{
"classes": [
{
"classId": "SSC",
"studentIds": [
"1"
]
},
{
"classId": "HSC",
"studentIds": [
"2",
"3"
]
}
],
"students": [
{
"_id": "1",
"student": {}
},
{
"_id": "2",
"student": {}
},
{
"_id": "3",
"student": {}
}
]
}
我希望进行聚合查询,使其返回如下所示的数据:
"classes": [
{
"classId": "SSC",
"students": [
{
"id": "1",
"student": {}
}
]
},
{
"classId": "HSC",
"students": [
{
"id": "2",
"student": {},
},
{
"id": "3",
"student": {},
}
]
}
]
在这个问题中,我有一系列的 ID。它应该过滤该 ID 的学生列表,然后获取该对象,并将该对象放入班级数组中。
我尝试使用 MongoDB 聚合来解决这个问题。但不幸的是,我无法为此编写查询。那么,我们能否使用聚合来实现上述情况呢?
我正在使用 Spring Boot 的 mongoTemplate。
英文:
In my mongodb I have the data as shown below:
{
"classes": [
{
"classId": "SSC",
"studentIds": [
"1"
]
},
{
"classId": "HSC",
"studentIds": [
"2",
"3"
]
}
],
"students": [
{
"_id": "1",
"student": {}
},
{
"_id": "2",
"student": {}
},
{
"_id": "3",
"student": {}
}
],
}
And I want an aggregation query such that it returns the data as shown below:
"classes": [
{
"classId":"SSC",
"students": [
{
"id": "1",
"student": {}
}
]
},
{
"classId":"HSC",
"students": [
{
"id": "2",
"student": {},
},
{
"id": "3",
"student": {}
}
]
}
]
In this I have list of ids. It should filter the students list for that id and take that object and place this object in class array.
I have tried to use mongodb aggregation for this problem. But unfortunately I am not able write query for that. So can we achieve the above scenario using aggregation.
I am using spring boot mongoTemplate.
答案1
得分: 1
你可以使用$map
和$filter
,
- 使用
$map
操作在classes
数组中创建students
字段,并在students
数组中进行$filter
操作,检查数组中是否存在符合条件的ids。
db.collection.aggregate([
{
$project: {
classes: {
$map: {
input: "$classes",
as: "c",
in: {
classId: "$$c.classId",
students: {
$filter: {
input: "$students",
cond: { $in: ["$$this._id", "$$c.studentIds"] }
}
}
}
}
}
}
}
])
英文:
You can use $map
and $filter
,
$map
inputclasses
array create students field and do$filter
in students array and check condition ids in array or not
db.collection.aggregate([
{
$project: {
classes: {
$map: {
input: "$classes",
as: "c",
in: {
classId: "$$c.classId",
students: {
$filter: {
input: "$students",
cond: { $in: ["$$this._id", "$$c.studentIds"] }
}
}
}
}
}
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论