Search code examples
mongodbmongodb-.net-driver

Join two documents in mongoDB even if there is no entry in the right joined collection


Please help me out by letting me know how to write the syntax for joining two collections in MongoDB. I want all the entries of the left joined collection. If there is no matching entry in the right collection then it should be populated as a blank field.

see below code,

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 List<Sample> Samples { get; set; }
}

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

I use below code for join collactions,

var data = _mongoDatabase.GetCollection<Instance>("Instance").Aggregate()
    .Lookup("Templates", "TemplateId", "TId", @as: "Template")
    .Lookup("Sample", "TemplateId", "TemplateId", @as: "Template.Samples")
    .Unwind("Template")
    .Unwind("Template.Samples")
    .As<Instance>()        
    .ToList();

Here what happening, if there is a document in Instance collection and no relevant matching document is present in Template or Sample collection then Instance document is also not coming to the list.

I want all Instance documents even if there is no matching Template or Sample document available.


Solution

  • preserveNullAndEmptyArrays - boolean Optional.

    If true, if the path is null, missing, or an empty array, $unwind outputs the document.

    If false, if path is null, missing, or an empty array, $unwind does not output a document.

    The default value is false.

    https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/#std-label-unwind-preserveNullAndEmptyArrays