我有两个集合。document
和 citation
. 它们的结构如下图所示。
# document
{id:001, title:'foo'}
{id:002, title:'bar'}
{id:003, title:'abc'}
# citation
{from_id:001, to_id:002}
{from_id:001, to_id:003}
我想查询被引用的文献信息(称为参考文献,用 "参考文献 "来表示)。to_id
)的每个文档。在SQL中,我会使用 document
桌左连接 citation
然后左键连接 document
来获取完整的引用信息(而不仅仅是它们的id)。
然而,我只能通过使用 $lookup
在MongoDB中。这是我的聚合流水线。
[
{'$lookup':{
'from': 'citation',
'localField': 'id',
'foreignField': 'from_id',
'as': 'references'
}}
]
我可以通过这个管道得到以下结果。
{
id:001,
title:'foo',
references:[{from_id:001, to_id:002}, {from_id:001, to_id:003}]
}
想要的结果是:
{
id:001,
title:'foo',
references:[{id:002, title:'bar'}, {id:003, title:'abc'}]
}
我找到了这个 回答 但似乎是一对一的关系,在我的情况下不适用。
EDIT:有人说MongoDB中应该避免使用join,因为它不是关系型数据库。我选择MongoDB是因为在我的案例中它比MySQL快得多。
你需要使用 $unwind
又 $lookup
在同一个系列上,那么你应该 $group
由 _id
以获得理想的结果。
试试下面的方法。
[
{
"$lookup": {
"from": "citation",
"localField": "_id",
"foreignField": "from_id",
"as": "references"
}
},
{
"$unwind": "$references"
},
{
"$lookup": {
"from": "doc",
"localField": "references.to_id",
"foreignField": "_id",
"as": "map"
}
},
{
"$unwind": "$map"
},
{
"$project": {
"_id": 1,
"title": 1,
"map_id": "$map._id",
"map_title": "$map.title"
}
},
{
"$group": {
"_id": "$_id",
"title": {
"$first": "$title"
},
"references": {
"$push": {
"id": "$map_id",
"title": "$map_title"
}
}
}
}
]