Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created July 7, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/a2e2e59b063c2338b0b9507e209ec59e to your computer and use it in GitHub Desktop.
Save dj-nitehawk/a2e2e59b063c2338b0b9507e209ec59e to your computer and use it in GitHub Desktop.
nested lookup example
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