我在 MongoDB 中查找 2 個集合時遇到問題我的資料庫由 3 個集合組成:PROJECT、CATEGORY 和 SUBCATEGORY,其中 1 個 PROJECT 可以在多個 CATEGORY 中,1 個 CATEGORY 可以有多個 SUBCATEGORY
專案
"project": [
{
_id: 234,
title: "proj 1",
description: "description 1",
category: [
{
_id: 1,
subcategory: [
{
_id: 11
},
{
_id: 12
}
]
},
{
_id: 2,
subcategory: [
{
_id: 21
},
{
_id: 23
}
]
}
]
},
類別
"category": [
{
_id: 1,
title: "cate 1",
subcategory: [
{
_id: 11,
},
{
_id: 12,
},
{
_id: 13,
},
{
_id: 14,
},
]
},
{
_id: 2,
title: "cate 2",
subcategory: [
{
_id: 21,
},
{
_id: 22,
},
{
_id: 23,
},
]
}
]
子類別
"subcategory": [
{
"_id": 11,
title: "subcate 11",
},
{
"_id": 12,
title: "subcate 12",
},
{
"_id": 13,
title: "subcate 13",
},
{
"_id": 14,
title: "subcate 14",
},
{
"_id": 21,
title: "subcate 21",
},
{
"_id": 22,
title: "subcate 22",
},
{
"_id": 23,
title: "subcate 23",
},
]
我想同時查找 categoryId 和 subcategoryId,但我一次只能查找其中一個,所以當我同時查找它們時,我無法將它們的關系重新連接在一起。例如,第一種方式,當我首先查找 subcategoryId 時,我得到了子類別的詳細資訊,但是當我嘗試查找 categoryId 時,包含子類別的類別詳細資訊會覆寫 subcategoryLookup。另一方面,當我首先查找 categoryId 時,我丟失了 subcategoryId 的資訊。
這是我想要的資料
[
{
"_id": 234,
"title": "proj 1"
"description: "description 1"
"category": [
{
"_id": 1,
"title": "cate 1"
"subcategory": [
{
"_id": 11,
"title": "subcate 11"
},
{
"_id": 12,
"title": "subcate 12"
}
],
},
{
"_id": 2,
"title": "cate 2"
"subcategory": [
{
"_id": 21,
"title": "subcate 21"
},
{
"_id": 23,
"title": "subcate 23"
}
],
}
],
}
]
我已經嘗試了很多方法,現在我處于這個階段,我得到了 CATEGORY 組而不是 PROJECT
https://mongoplayground.net/p/LXJ-BsTWX3a
請幫幫我,我想不出一種將這些資料組織在一起的方法
uj5u.com熱心網友回復:
代碼是
db.project.aggregate([
{
$match: {
_id: 234
}
},
{
"$unwind": "$category"
},
{
"$lookup": {
"from": "subcategory",
"localField": "category.subcategory._id",
"foreignField": "_id",
"as": "category.subcategory"
}
},
{
"$lookup": {
"from": "category",
"localField": "category._id",
"foreignField": "_id",
"as": "joinFortitle"
}
},
{
"$addFields": {
"category.title": {
"$arrayElemAt": [
"$joinFortitle",
0
]
}
}
},
{
"$addFields": {
"category.title": "$category.title.title"
}
},
{
"$group": {
"_id": "$_id",
"title": {
"$first": "$title"
},
"description": {
"$first": "$description"
},
"category": {
$push: "$category"
}
}
}
])
作業蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443234.html
