Keith Nicholas
Keith Nicholas

Reputation: 44288

How to deal with C# object references in MongoDB?

I'm wondering how to handle when an object is used in multiple locations. Given th following code (just example code) :-

 public class Group
    {          
        public ObjectId Id { get; set; }
        public string Name { get; set; }
        public List<Person> People { get; set; }
        public List<Meeting> Meetings { get; set; }
    }

    public class Meeting
    {          
        public string Subject { get; set; }
        public List<Person> Attendees { get; set; }
    }

    public class Person
    {            
        public string Name { get; set; }
    }

If I store the group as a mongodb document, it will serialize all the people and meetings. However the same Person object can be refered to in the People List and as an attendee of a meeting. However once serialized they become separate objects. How can I maintain that the same "Person" object is both in the People list and Meetings list?

Or is there are better way to model this? One thing that could be done is put the "People" in a separate Document and embeded / reference it? This then starts to create more and more separate collections, ideally I'd like to maintain references within a single document.

Or within a document should I Id each person and have one master list and then only store lists of Ids in the "Meetings" and use some kind of helper method to resolve the Id from the master list? Can be done, but a little bit ugly.

Upvotes: 3

Views: 466

Answers (1)

Lummo
Lummo

Reputation: 1169

I'm not an expert with MongoDB but I think in this scenario each of these items should be a separate collection with references to get the results you are after.

Meetings have a Group ID and a list of Person ID attendees. Groups have a list of Person ID members (people). If a person can only belong to one group then they can have a single group ID.

Once they go into the database the only option you have with your existing design is checking for name equality which as you say can be done but doesn't seem like the right approach.

Essentially you are using the embedded relationship model with how you are storing 'Person' in 'Group' and 'Meeting' but if you want the same 'Person' object for both then you need to use references for Attendees or both. This seems like the simplest approach to me while not 'fighting' against the standard behaviour.

Upvotes: 2

Related Questions