在MongoDb中,我想创建一个视图,该视图结合了2个集合中的数据。
结构: 事件:ID,名称,日期,位置(LocationId,日期),位置 ID,名称。 EventView :名称,日期,位置(LocationName,日期)。
示例:
事件:
[{ Id: 1, Name: 'Event 1', Date:'2019-01-16', [{ LocationId: 1, Date:'2019-01-16'}, { LocationId: 2, Date: '2019-01-17'}]}, { Id:1, Name: 'Event 2', Date:'2019-01-18', [{ LocationId: 1, Date:'2019-01-18'}]}]
位置:
[{ Id: 1, Name: 'London' }, { Id: 2, Name: 'New York' }]
当前代码
db.createView("EventView", "Event",
[
{ $lookup: { from: "Location", localField: "Locations.Id", foreignField: "Id", as: "locations" } },
{ $project: { Id: 1, Name: 1, Date: 1, Locations: 1, "locations.Id": 1, "locations.Name": 1 } }
]
)
当前输出:
[{ Name: 'Event 1', Date: '2019-01-16', Locations:[{ LocationId: 1, Date: '2019-01-16' }, { LocationId: 2, Date: '2019-01-17' }], locations: [{ Id: 1, Name: 'London' }, { Id: 2, Name: 'New York' }]}, { Name: 'Event 2', Date: '2019-01-18', Locations: [{ LocationId: 1, Date:'2019-01-18' }], locations: [{ Id: 1, Name: 'London' }]}]
所需的输出:
[{ Name: 'Event 1', Date: '2019-01-16', Locations:[{ LocationName: 'London', Date: '2019-01-16' }, { LocationName: 'New York', Date: '2019-01-17' }]}, { Name: 'Event 2', Date: '2019-01-18', Locations: [{ LocationName: 'London' Date:'2019-01-18' }]}]
问:我需要在代码中进行哪些更改,以便像所需的输出示例中那样映射 Locations 属性?