Search code examples
c#mongodbmongodb-.net-driver

MongoDb one-to-many mapping


I'm trying to make a one-to-many relationship with MongoDb, but stucked on joining the two collections. I did an example below to see how I am doing this now.

// schools collection
{
  _id: ObjectId("5ef206d1d21c573718ae6eda")
  name: "Hogwarts School of Witchcraft and Wizardry"
}

// students collection
{
  _id: ObjectId("5efed5df8b28770c2cb344b9"),
  school_id: ObjectId("5ef206d1d21c573718ae6eda")
  firstName: "Harry"
  lastName: "Potter"
}

And model classes in the .net project:

public class School
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    
    public string Name { get; set; }
    public List<Student> Students { get; set; }
}

public class Student
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    
    [BsonRepresentation(BsonType.ObjectId)]
    [Required]
    public string School_id { get; set; }
    
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

How can I map the students into the school object? I tried these codes, but none of them work.

// 1st attempt
var q = _schools.Aggregate().Lookup<School, Student, School>(_students, school => school.Id, student 
=> student.school_id, a => a.Students);

// 2nd attempt
var q = from school in _schools.AsQueryable()
        join student in _students.AsQueryable() on school.Id equals student.school_id into students
        select new School()
        {
            Students = students
        };

var result = q.ToList();

What am I missing?


Solution

  • Actually both code snippets are work, the only thing was wrong, that I mispelled the school_id value in the database and referenced to a non-existing School document.