需要在mongodb中使用自定义结果填充块中的所需结果



我有四个集合person , other_details, occupation_details, bank_details,如下所述

person =>[
{
id : 1,
name : 'john',
other_details : 1023
},
{
id : 2,
name : 'mark',
other_details : 99
}
]

other_details => [
{
id: 1023,
married: false,
occupation_details: 144,
bank_details : 10
},
{
id: 99,
married: true,
occupation_details: 45,
bank_details : 11
}
]
occupation_details => [
{
id: 144,
comp_name : 'oscorp inc.'
},
{
id: 45,
comp_name : 'tesla inc.'
}
]
bank_details => [
{
id: 10,
bank : 'Bank of canada'
},
{
id: 11,
bank : 'Peoples bank of canada'
}
]

我正在使用带有nodejs 的mongoose库

// id = 1
person.findById(id).populate({
path: 'other_details',
populate: [
{
path: 'occupation_details'
},
{
path: 'bank_details'
}
]
})

因此,上面查询的结果如下=>

{
id : 1,
name : 'john',
other_details : {
id: 1023,
married: false,
occupation_details: {
id: 144,
comp_name : 'oscorp inc.'
},
bank_details : {
id: 10,
bank : 'Bank of canada'
}
}
}

但出于某些原因,我想要下面这样的结果

{
id : 1,
name : 'john',
other_details : {
id: 1023,
married: false,
occupation_details: {
id: 144,
comp_name : 'oscorp inc.'
},
bank_details : 10,
custom_bank_details : {
id: 10,
bank : 'Bank of canada'
}
}
}

我需要的更改如下,bank_details对象应该与id一起存在,并且来自其他集合的填充的bank_details数据应该以custom_bank_details的其他对象名称出现

bank_details : 10,
custom_bank_details : {
id: 10,
bank : 'Bank of canada'
}

更新:

您可以使用virtual将银行详细信息填充到一个新字段中。类似的东西

OtherDetailsSchema.virtual('custom_bank_details', {
ref: 'BankDetails',
localField: 'bank_details',
foreignField: '_id',
justOne: true
});
Person.findById(id).populate({
path: 'other_details',
populate: [
{path: 'occupation_details'},
{path: 'custom_bank_details'}
]})

原始

我不是猫鼬用户,所以我不确定是否可以填充到新的字段名。如果可行的话,您可以很容易地实现使用聚合和查找。

类似的东西

person.aggregate([
{"$lookup":{
"from":"other_details",
"let":{"other_details":"$other_details"},
"pipeline":[
{"$match":{"$expr":{"$eq":["$id","$$other_details"]}}},
{"$lookup":{
"from":"occupation_details",
"localField":"occupation_details",
"foreignField":"id",
"as":"occupation_details"
}},
{"$unwind":"$occupation_details"},
{"$lookup":{
"from":"bank_details",
"localField":"bank_details",
"foreignField":"id",
"as":"custom_bank_details"
}},
{"$unwind":"$custom_bank_details"},
],
"as":"other_details"
}},
{"$unwind":"$other_details"}
])

工作示例https://mongoplayground.net/p/5Kee0tBQmTd

最新更新