我正在尝试聚合以下文档,以将参与者作为嵌套数组中的对象。
{
"name": "EXAMPLE",
"schedules": [
{
"schedule_id": "id1",
"participants": [
"participant_id1",
"participant_id2"
],
},
{
"schedule_id": "id2",
"participants": [
"participant_id1",
"participant_id2"
],
},
{
"schedule_id": "id3",
"participants": [
"participant_id1"
],
},
],
}
因此,我写了以下管道:
[
{
$unwind: {
path: "$schedules",
includeArrayIndex: "index",
preserveNullAndEmptyArrays: true,
}
},
{
$unwind: {
path: "$schedules.participants",
includeArrayIndex: "index",
preserveNullAndEmptyArrays: true,
}
},
{
$lookup: {
from: "customers",
localField: "schedules.participants",
foreignField: "_id",
as: "participants",
}
},
{
$project: {
"participants.address": 0,
"participants.birthday": 0,
}
},
{
$unwind: {
path: "$participants",
preserveNullAndEmptyArrays: true,
}
},
{
$group:
{
_id: "$_id",
name: {
$first: "$name",
},
schedules: {
$first: "$schedules",
},
}
},
]
- 此管道中的第一步是展开时间表数组,以获取文档中的每个单独的时间表
- 第二步是展开参与者,因为我需要参与者id来完成第三步中的查找过程
- 第三步是在customers集合中查找参与者,返回的将是一个customer对象
- 在第四步中,我将使用project从给定的参与者中删除不必要的字段
- 在第五步中,我再次使用放松来获得单个参与者(我知道也可以使用$first运算符(
- 在第六步中,我将分组
我正试图将步骤3中的每个参与者添加到参与者数组中相应的时间表对象中,文档应该是这样的:
{
"name": "EXAMPLE",
"schedules": [
{
"schedule_id": "id1",
"participants": [
{
id: "id1",
"name": "name1"
},
{
id: "id2",
"name": "name2"
},
],
},
{
"schedule_id": "id2",
"participants": [
{
id: "id1",
"name": "name1"
},
{
id: "id2",
"name": "name2"
},
],
},
{
"schedule_id": "id3",
"participants": [
{
id: "id1",
"name": "name1"
},
],
},
],
}
你有正确的想法,你可以简化你的管道,从而使其更容易重建,第二个$unwind
是多余的,删除它将允许我们只使用1个组阶段来重建对象。这显然要简单得多。
db.collection.aggregate([
{
$unwind: {
path: "$schedules",
includeArrayIndex: "index",
preserveNullAndEmptyArrays: true,
}
},
{
$lookup: {
from: "customers",
localField: "schedules.participants",
foreignField: "_id",
as: "participants",
}
},
{
$project: {
"participants.address": 0,
"participants.birthday": 0,
}
},
{
$group: {
_id: "$_id",
schedules: {
$push: {
schedule_id: "$schedules.schedule_id",
participants: "$participants"
}
},
name: {
$first: "$name"
}
}
}
])
Mongo游乐场