I have come across a situation where it would be better to represent a particular part of my domain model as relational. I read the section on database references in MongoDB and understand you can provide references to multiple documents by providing a JSON array of $ref references to various documents in a foreign collection.
All the examples I’ve seen for adding a reference to a foreign document in code have been only for a single document and they’ve created a public property of type MongoDBRef. There is a lot of unnecessary overhead with this approach, in my opinion, but it also doesn’t make it clear what to do about storing references to multiple documents.
If you would like to provide a one-to-many relationship between foreign documents in Mongo, is it necessary to provide a collection property containing MongoDBRef objects? Is it possible to stick to a collection of standard entity objects in my C# code and map it to Mongo documents using BsonClassMap?
Below is a simple class that represents the model I currently have. It seems to be saving the document and references correctly, but I don’t like exposing a public collection of MongoDBRef objects and the overhead it takes to add new documents for anybody that uses the Person class.
If it matters, I’m using MongoDB 2.0 and their C# driver.
// This is how my class currently looks
public class Person
{
public string Name { get; set; }
public List<MongoDBRef> Vehicles { get; private set; }
public Person()
{
Vehicles = new List<MongoDBRef>();
}
}
// This is what I want my class to look like
public class Person
{
public string Name { get; set; }
public List<Vehicle> Vehicles { get; private set; }
public Person()
{
Vehicles = new List<Vehicle>();
}
}
DBRefs are not the appropriate tool for storing references to a known document type. Instead just save the _id values of the referred documents in your collection. Given a good mapping library (not sure about C# but the C# equivalent of pymongo, mongoose, morphia, etc.) it will allow you to do exactly what you want.
DBRefs should only be used if you do not know at compile time what kind of document you need to store a reference to (e.g. a “content” field that either holds an Image or a Text, etc.).