-
Notifications
You must be signed in to change notification settings - Fork 226
Inheritance
Inheritance has first class support in MongoDB-CSharp. We have chosen to use discriminators to define which type of class is stored in the database. This way, all entities in the inheritance chain are all stored in the same MongoDB collection. This allows queries to be issues for types in the inheritance chain at once.
Any value is allowed for the discriminator so there is no need to have a strong link between a type’s name and it’s discriminator value in the database. The only caveat to this is that you must let us know about any subclasses prior to deserializing them. Otherwise, we wouldn’t know about the mapping. This is done off of a MongoConfiguration object using the Map() method.
By default, we use an “_t” as the discriminator key because it is small. Since keys are stored for every value, it is better to keep them smaller in most cases.
Below is an example of an animal hierarchy and their default discriminator values.
abstract class Animal
{
public Oid Id { get; set; }
public int Age { get; set; }
}
//Bear will have a discriminator value of "Bear"
class Bear : Animal
{ }
//a MongoDB Bear document would like {_id: "ObjectId(etc...)", _t: "Bear", Age: 3}
//Cat will have a discriminator value of "Cat"
abstract class Cat : Animal
{ }
//Tiger will have a discriminator value of ["Cat", "Tiger"]
class Tiger : Cat
{ }
//a MongoDB Tiger document would like {_id: "ObjectId(etc...)", _t: ["Cat", "Tiger"], Age: 3}
//Lion will have a discriminator value of ["Cat", "Lion"]
class Lion : Cat
{ }
//a MongoDB Lion document would like {_id: "ObjectId(etc...)", _t: ["Cat", "Lion"], Age: 3}
When using Typed Collections, MongoDB-CSharp automatically adds in the relevant discriminators when saving the documents and when querying. Below are some examples:
This will pull back all animals over the age of 10.
//C# code
GetCollection<Animal>().Find(x => x.Age > 10);
//json query
{ "Age" : {$gt: 10 } }
This will pull back all Cats over the age of 10.
//C# code
GetCollection<Cat>().Find(x => x.Age > 10);
//json query
{"_t": "Cat", "Age" : {$gt: 10 } }
This will pull back all Tigers over the age of 10.
//C# code
GetCollection<Tiger>().Find(x => x.Age > 10);
//json query
{"_t": ["Cat", "Tiger"], "Age" : {$gt: 10 } }