I am currently trying to figure out, how Nosql databases handle relations and what the unique Id of a Document really means.
Maybe I am expecting too much of MongoDb or I haven't grasp the concept of relations in NoSQL databases yet.
Basically, the following test fails, and I wonder how one would model such a relation between Users and Groups (which is a 1 : 0..N relation).
[TestFixture]
public class MongoDbExamples
{
private MongoServer _mongoServer;
[TestFixtureSetUp]
public void FixtureSetUp()
{
_mongoServer = MongoServer.Create();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
_mongoServer.Disconnect();
}
[Test]
public void RelationTest()
{
var database = _mongoServer.GetDatabase("StackoverflowExamples");
var p = new Person() { Name = "Testperson" };
var persons = database.GetCollection<Person>("Persons");
persons.Save<Person>(p);
var group = new Group() { Description = "A fancy descriptor" };
group.Add(p);
var groups = database.GetCollection<Group>("Groups");
groups.Save<Group>(group);
var readPerson = persons.FindOneById(p.Id);
readPerson.Name = "a different name";
// since the id hasn't change this is an update of the original person:
persons.Insert<Person>(readPerson);
// and I thought that it should be reflected in the group as well:
var readGroup = groups.FindOneById(group.Id);
Assert.AreEqual(readPerson.Id, readGroup.persons[0].Id); // this passes, the id is the same
Assert.AreEqual(readPerson.Name, readGroup.persons[0].Name); // this fails, the groups person still has the old name
}
}
Are there best practices for such relations? E.g. Should search for all person in all Collections/Documents and exchange those found with the matching person of the persons collection? Or are relations something which NoSQL databases aren't good at and I should avoid relations (I wonder how to use a NoSQL-DB in a bigger system with more complex object graphs then)?
There is no such thing as relations or auto-updates of related collections. Seems like you expect mongo to behave like an ORM, but that is not what it does, at least not with the C# driver. If you want to save a Person and a Group you will have to save them both individually.
Rather than storing full person objects inside the group objects, you should store just the person ids instead. Then use those Ids to do a lookup of the person when you need the person data.
Also, you may wan to read the docs on dbref.
http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef