Search code examples
mongodbmongodb-.net-driver

Include object of child object using MongoDB driver .net core


I want to include object in the main collection's child object, I tried below code but it didn't work. Can someone help? Here I want to include "Sample" object in "Template" when getting collection of "Instance".

public class Instance
{
    public long IId { get; set; }
    public string Name { get; set; }
    public long TemplateId { get; set; }
    public Template Template { get; set; }
}

public class Template
{
    public long TId { get; set; }
    public string Name { get; set; }
    public long SampleId { get; set; }
    public Sample Sample { get; set; }
}

public class Sample
{
    public long SId { get; set; }
    public string Name { get; set; }        
}


string connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);

var db = client.GetDatabase("test");
var instances = db.GetCollection<Instance>("Instances");
var resultOfJoin = instances.Aggregate()
    .Lookup("Template", "TemplateId", "TId", @as: "Template")
    .Lookup("Sample", "SampleId", "SId", @as: "Template.Sample")
    .Unwind("Template")
    .Unwind("Template.Sample")
    .As<Instance>()
    .ToList();

Solution

  • I found the solution by try and error, We need to add a local filed key with the object name as below,

    .Lookup("Sample", "Template.SampleId", "SId", @as: "Template.Sample")

    var resultOfJoin = instances.Aggregate()
        .Lookup("Template", "TemplateId", "TId", @as: "Template")
        .Lookup("Sample", "Template.SampleId", "SId", @as: "Template.Sample")
        .Unwind("Template")
        .Unwind("Template.Sample")
    .As<Instance>()
    .ToList();