我目前正在研究一个小型聊天轮盘赌应用程序。为此,我在后端使用MongoDB和NodeJS。要列出所有聊天频道,我想加入两个收藏集。第一个(聊天)的元素具有嵌套数组:
{
title: 'example 1',
country: 'UK',
...
chat: [
{
details: 'chat1 infos',
channel: [
'5ea3257d4b861a5aa0d03111',
'5ea3257d4b861a5aa0d03122'
]
},
{
details: 'chat2 infos',
channel: [
'5ea3257d4b861a5aa0d03333'
]
}
]
}
第二个(通道)存储所有详细信息:
{
_id: '5ea3257d4b861a5aa0d03111',
title: 'Channel1',
details: 'Channel1 Details'
},
{
_id: '5ea3257d4b861a5aa0d03222',
title: 'Channel2',
details: 'Channel2 Details'
},
{
_id: '5ea3257d4b861a5aa0d03333',
title: 'Channel3',
details: 'Channel13 Details'
}
结果应如下所示:
{
title: 'example 1',
country: 'UK',
...
chat: [
{
details: 'chat1 infos',
channel: [
{
_id: '5ea3257d4b861a5aa0d03111',
title: 'Channel1',
details: 'Channel1 Details'
},
{
_id: '5ea3257d4b861a5aa0d03222',
title: 'Channel2',
details: 'Channel2 Details'
}
]
},
{
details: 'chat2 infos',
channel: [
{
_id: '5ea3257d4b861a5aa0d03333',
title: 'Channel3',
details: 'Channel13 Details'
}
]
}
]
}
我尝试通过使用$ lookup:
db.collection('chats').aggregate([
{ "$lookup": {
"from": "channel",
"localField": "chat.channel",
"foreignField": "_id",
"as": "chat.channel"
} }
]);
但是,我将每个频道的所有结果合并在一起。无论通道中包含哪个ID。如何加入集合以获取描述的结果?
您可以遵循此部分
您可以使用填充
let _doc =await firstModel.find().populate("channels")
尝试一下
db.chats.aggregate([
{
$unwind: "$chat" // we need this as we have an array of chats, and each chat element has an array of channels
},
{
$lookup: {
from: "channels", // will use pipeline in lookup to get rid of multiple group stages
let: {
channelIds: "$chat.channel"
},
pipeline: [
{
$match: {
$expr: {
$in: [
"$_id", // _id of channel
"$$channelIds" // channel ids from chat.channel array
]
}
}
}
],
as: "chat.channel"
}
},
{
$group: {
_id: "$_id", // group the unwinded chat array
title: {
$first: "$title"
},
country: {
$first: "$country"
},
chat: {
$push: "$chat"
}
}
}
])