Created
July 7, 2021 15:40
-
-
Save dj-nitehawk/a2e2e59b063c2338b0b9507e209ec59e to your computer and use it in GitHub Desktop.
nested lookup example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MongoDB.Bson; | |
using MongoDB.Driver; | |
using MongoDB.Entities; | |
using System.Threading.Tasks; | |
namespace ReferencedRelationshipExample | |
{ | |
public class Author : Entity | |
{ | |
public string Name { get; set; } | |
public Many<Book> Books { get; set; } | |
public Author() => this.InitOneToMany(() => Books); | |
} | |
public class AuthorWithBooks : Author | |
{ | |
public BookWithChapters[] AllBooks { get; set; } | |
} | |
public class Book : Entity | |
{ | |
public string Title { get; set; } | |
public One<Author> Author { get; set; } | |
public Many<Chapter> Chapters { get; set; } | |
public Book() => this.InitOneToMany(() => Chapters); | |
} | |
public class BookWithChapters : Book | |
{ | |
public Chapter[] AllChapters { get; set; } | |
} | |
public class Chapter : Entity | |
{ | |
public string Title { get; set; } | |
public One<Book> Book { get; set; } | |
} | |
public static class Program | |
{ | |
private static async Task Main() | |
{ | |
await DB.InitAsync("test"); | |
for (int a = 1; a <= 3; a++) | |
{ | |
var author = new Author { Name = $"author {a}" }; | |
await author.SaveAsync(); | |
for (int b = 1; b <= 3; b++) | |
{ | |
var book = new Book { Title = $"author {a} book {b}", Author = author }; | |
await book.SaveAsync(); | |
await author.Books.AddAsync(book); | |
for (int c = 1; c <= 3; c++) | |
{ | |
var chapter = new Chapter { Title = $"author {a} book {b} chapter {c}", Book = book }; | |
await chapter.SaveAsync(); | |
await book.Chapters.AddAsync(chapter); | |
} | |
} | |
} | |
var let = BsonDocument.Parse("{ book_id: '$_id' }"); | |
var pipeline = PipelineDefinition<Book, BookWithChapters>.Create(new IPipelineStageDefinition[] { | |
PipelineStageDefinitionBuilder.Match<Book>("{$expr: { $eq: ['$Author.ID', '$$book_id'] }}"), | |
PipelineStageDefinitionBuilder.Lookup<Book, Chapter, BookWithChapters>( | |
foreignCollection: DB.Collection<Chapter>(), | |
localField: b => b.ID, | |
foreignField: c => c.Book.ID, | |
@as: bwc => bwc.AllChapters) | |
}); | |
var result = await DB | |
.Fluent<Author>() | |
.Lookup<Author, Book, BookWithChapters, BookWithChapters[], AuthorWithBooks>( | |
foreignCollection: DB.Collection<Book>(), | |
let: let, | |
lookupPipeline: pipeline, | |
@as: awb => awb.AllBooks) | |
.ToListAsync(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment