Mongodb: reverse document tree as a view (using C# driver)

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Mongodb: reverse document tree as a view (using C# driver)



I'm trying the following (simplistic scenario):



I have two documents that look like this (cinema has timeslots, timeslot has a movie):


{
"_id":"5b5dd8932dc7aa1e180f8c23",
"Name":"Cinema 1",
"TimeSlots":[
{
"Start":"2018-07-29T16:00:00.000Z",
"End":"2018-07-29T18:30:00.000Z",
"Movie":{
"_id":"5b5dd8932dc7aa1e180f8c24",
"Name":"Movie 1"
}
},
{
"Start":"2018-07-29T15:00:00.000Z",
"End":"2018-07-29T17:15:00.000Z",
"Movie":{
"_id":"5b5dd8932dc7aa1e180f8c25",
"Name":"Movie 2"
}
}
]
}

{
"_id":"5b5dd8932dc7aa1e180f8c26",
"Name":"Cinema 2",
"TimeSlots":[
{
"Start":"2018-07-29T18:00:00.000Z",
"End":"2018-07-29T20:30:00.000Z",
"Movie":{
"_id":"5b5dd8932dc7aa1e180f8c24",
"Name":"Movie 1"
}
},
{
"Start":"2018-07-29T19:00:00.000Z",
"End":"2018-07-29T21:15:00.000Z",
"Movie":{
"_id":"5b5dd8932dc7aa1e180f8c25",
"Name":"Movie 2"
}
}
]
}



I'd like to reverse the tree structure (so I have movies that have timeslots, which are linked to cinemas). In C# using LINQ I would do the following:


var movies = cinemas
.SelectMany(cinema => cinema.TimeSlots)
.Select(timeSlot => timeSlot.Movie)
.Distinct(new MovieEqualityComparer())
.Select(movie =>
{
movie.TimeSlots = cinemas
.SelectMany(cinema => cinema.TimeSlots)
.Where(timeSlot => timeSlot.Movie.Id == movie.Id)
.ToList();

return movie;
})
.ToList();



I'm wondering how one would achive this using the aggregate functions and a aggregate pipeline. I've tried several options including $project, $unwind and $group but I don't seem to be able to achieve the result I want. Any help is appriciated.


$project


$unwind


$group



This is what I have so far:


[
{
$unwind:{ path:'$TimeSlots' }
},
{
$unwind:{ path:'$TimeSlots.Movie' }
},
{
$group:{
_id:'$TimeSlots.Movie._id',
movies:{ $addToSet:'$TimeSlots.Movie' } }
},
{ $project: { movieId: '$_id'} } }
]



Which results into a similar result of my LINQ query up until the distinct.









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

gC98vVMc,IIZFgwF20 tl,Y,o,o6mf5 kmjRYKnzDURP3Dg7BsXUtW1K B8C,Y4UuVM,98OOhzRKyxgCcu22kab6BN
aVT3 VPBghlpe30IX41X1 LO,hMJzWKNVNz8pl6,yKSB3ctSIifV 2FsbWCGXW,GdI78fY 7

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results