我有2个收藏集。
案例
_id: ObjectId.
name: string.
info: {
[here can be many different fields with diff types]
entities: [
{ role: string;
id: ObjectId;
} <--- here can be a lot of entities
]
}
实体
_id: ObjectId.
type: string,
name: string,
info: {
[here can be many different fields with diff types]
}
我需要检索所有案例,并且对于每个case.info.entities对象,我需要具有字段 data ,该字段等于实体文档(case.info.entities.id === entity_id)
示例我需要的东西
_id: ObjectId.
name: string.
info: {
[here can be many different fields with diff types]
entities: [
{ role: string;
id: ObjectId;
data: {
_id: ObjectId.
type: string,
name: string,
info: {
[here can be many different fields with diff types]
}
}
} <--- here can be a lot of entities
]
}
如何正确执行操作?
答案 0 :(得分:0)
您几乎完成了所有操作。根据您的查询和模型,我在下面给出了查询(字段名称可能不同)。希望对您有所帮助。
db.cases.aggregate([
{ $unwind: '$info.relatedEntities' },
{ $lookup: {
from: 'entities',
localField: 'info.relatedEntities.entity',
foreignField: '_id',
as: 'info.relatedEntities.entityObject'
}
},
{ $group: {
_id: {
_id : '$_id',
templateType : '$templateType',
name : '$name',
info : {
address : "$info.address",
}
},
'relatedEntities': {
$push: {
role : '$info.relatedEntities.role',
entity : '$info.relatedEntities.entity',
data : { $arrayElemAt: [ '$info.relatedEntities.entityObject', 0 ] }
}
}
}
},
{
$project : {
_id : '$_id._id',
name : '$_id.name',
templateType : '$_id.templateType',
info : {
address : '$_id.info.address',
entities : '$relatedEntities'
}
}
}
]).pretty()