Springboot GET API显示多个集合根据Id进行梳理后的响应



我正在使用mongoDB的Springboot应用程序。我正在创建一个GET API,它从DB返回数据。我的要求是,我想在组合来自多个集合的数据后返回响应,而无需实际更改DB数据或模式。

为例:

MainCollection:

{
_id: 123, name: abc, value: 132,
subCollectionDetails: {
subCollectionId : 1111-1111,
subCollectionOtherValues: "Some data", 
}
},
{
_id: 124, name: fff, value: 132,
subCollectionDetails: {
subCollectionId : 1111-2222,
subCollectionOtherValues: "Some data", 
}
}.
{
_id: 125, name: abc, value: 132,
subCollectionDetails: {
subCollectionId : 1111-3333,
subCollectionOtherValues: "Some data", 
}
}

SubCollectionId:

{
_id: 1111-1111, 
subCollectionName : "sub1",
subCollectionPresent : True 
}
{
_id: 1111-2222, 
subCollectionName : "sub1",
subCollectionPresent : True 
}

最终GET API响应response:

{
_id: 123, name: abc, value: 132,
subCollectionDetails: {
_id: 1111-1111, 
subCollectionName : "sub1",
subCollectionPresent : True 
subCollectionOtherValues: "Some data", 
}
},
{
_id: 124, name: fff, value: 132,
subCollectionDetails: {
_id: 1111-2222, 
subCollectionName : "sub1",
subCollectionPresent : True 
subCollectionOtherValues: "Some data", 
}
}.
{
_id: 125, name: abc, value: 132,
subCollectionDetails: {
}
}

该查询应该返回您想要的内容:

db.main.aggregate([
{
$lookup: {
from: "sub",
localField: "subCollectionDetails.subCollectionId",
foreignField: "_id",
as: "sub_lookup"
}
},
{
$project: {
_id: true,
name: true,
value: true,
subCollectionDetails: {
$mergeObjects: [
"$subCollectionDetails",
{$arrayElemAt: ["$sub_lookup",0]}
]
}
}
},
{
$project: {
"subCollectionDetails.subCollectionId": false
}
}
])

你可以在这里运行https://mongoplayground.net/p/k-vkqoaH8nd

可以使用DTO投影作为接口或类。哪些字段是必需的,哪些字段通过getter方法被带入接口投影,或者在DTO类中,您也可以定义您想要的字段。

相关内容

  • 没有找到相关文章