我正在嘗試將一個專案添加到聚合中的陣列中,但似乎堅持了幾天。這是它的樣子:
db={
Students: [
{
"id": "123",
"title": "John",
"marks_in_subjects": [
{
"marks": 90,
"subject_id": "abc"
},
{
"marks": 92,
"subject_id": "def"
}
]
}
],
Subjects: [
{
"id": "abc",
"name": "math"
},
{
"id": "def",
"name": "physics"
}
]
}
我對新欄位進行專案和連接標題,如下所示:
db.Students.aggregate([
{
$unwind: "$marks_in_subjects"
},
{
"$lookup": {
"from": "Subjects",
"localField": "marks_in_subjects.subject_id",
"foreignField": "id",
"as": "subjects"
}
},
{
$unwind: "$subjects"
},
{
$project: {
_id: "$_id",
title: "$title",
titleAll: {
$concat: [
"$title",
" > ",
"$subjects.name",
]
},
}
},
])
這是我得到的輸出:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"title": "John",
"titleAll": "John \u003e math"
},
{
"_id": ObjectId("5a934e000102030405000000"),
"title": "John",
"titleAll": "John \u003e physics"
}
]
現在,我希望我的輸出在陣列中包含只有真正標題的第一項,然后列出所有這些,如下所示:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"title": "John",
"titleAll": "John"
},
{
"_id": ObjectId("5a934e000102030405000000"),
"title": "John",
"titleAll": "John \u003e math"
},
{
"_id": ObjectId("5a934e000102030405000000"),
"title": "John",
"titleAll": "John \u003e physics"
}
]
有沒有辦法實作它?我嘗試使用 $cond,但似乎不起作用。這是Mongo游樂場的鏈接
uj5u.com熱心網友回復:
你可以用更簡單的方式來做到這一點:
沒有必要一次$unwind又一次$group。缺少的步驟是將 連接title到titleAll陣列。
db.Students.aggregate([
{
$lookup: {
from: "Subjects",
localField: "marks_in_subjects.subject_id",
foreignField: "id",
as: "subjects"
}
},
{
$project: {subjects: "$subjects.name", title: 1}
},
{
$addFields: {
titleAll: {
$map: {
input: "$subjects",
as: "item",
in: {$concat: ["$title", " > ", "$$item"]}
}
}
}
},
{
$project: {
title: "$title",
titleAll: {"$concatArrays": ["$titleAll", ["$title"]]}
}
},
{
$unwind: "$titleAll"
}
])
示例 MongoDB Playground
uj5u.com熱心網友回復:
$unwind$lookup$group- 分組_id。獲取title欄位和subjects陣列(第 4 階段需要此欄位)。$setsubjects-通過添加第一個檔案和現有檔案來修改欄位subjects。$unwind- 解構subjects欄位。$project- 裝飾輸出檔案。
db.Students.aggregate([
{
$unwind: "$marks_in_subjects"
},
{
"$lookup": {
"from": "Subjects",
"localField": "marks_in_subjects.subject_id",
"foreignField": "id",
"as": "subjects"
}
},
{
$group: {
_id: "$id",
title: {
$first: "$title"
},
subjects: {
$push: {
$first: "$subjects"
}
}
}
},
{
$set: {
subjects: {
$concatArrays: [
[
{
titleAll: "$title"
}
],
{
$map: {
input: "$subjects",
in: {
titleAll: {
$concat: [
"$title",
" > ",
"$$this.name"
]
}
}
}
}
]
}
}
},
{
$unwind: "$subjects"
},
{
$project: {
_id: 1,
title: 1,
titleAll: "$subjects.titleAll"
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474018.html
標籤:mongodb
