C# Load Related document based on List<string>

My Document structure is as follow.

public class Person{
 string id,  
 string name,
list<string> Addresses. // stores id's from Address document
//bsonignore
Address AddressDetail
} 

public class Address{
string id,
string address1,
string address2 
}

When I load person details , I want to load all the addresses based on id’s present in the List of Person document.

Either MongoDB way or C# Way will atleast give me a hint to resolve this.

Hi, @Manish_Pandit,

Welcome to the MongoDB Community Forums. I understand that you’re trying to represent a Person with a list of Addresses. The easiest way to model this in MongoDB is with subdocuments:

{
  _id: ObjectId("6270582dfe5ecac36c5d315d"),
  Name: "Jane Doe",
  Addresses: [
    { AddressLine: "123 Nowhere Street", city: "Somewhere", state: "NY" },
    { AddressLine: "456 Somewhere Avenue", city: "Nowhere", state: "NY" }
  ]
}

The .NET/C# driver will map collections of subdocuments automatically to your POCOs.

public class Person {
  public ObjectId Id { get; set; }
  public string Name { get; set; }
  public IEnumerable<Address> Addresses { get; set; }
}

public class Address {
  public string AddressLine { get; set; }
  public string City { get; set; }
  public string State { get; set; }
}

Sincerely,
James

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.