I’m new to MongoDB and was wondering about querying for domain objects with registered BsonClassMaps.
Consider the following Mappings:
BsonClassMap.RegisterClassMap<VoyageNumber>(cm =>
{ cm.MapField<string>(p => p.Id); });
BsonClassMap.RegisterClassMap<Schedule>(cm =>
{ cm.MapField<DateTime>(p => p.EndDate); cm.MapField<DateTime>(p => p.StartDate); });
BsonClassMap.RegisterClassMap<Voyage>(cm =>
{ cm.MapIdField<VoyageNumber>(p => p.VoyageNumber); cm.MapField<Schedule>(p => p.Schedule); });
The domain entity is “Voyage”. In this simple example it consists of a complex type “Schedule” (with start date and end date) and a VoyageNumber (with a string id field).
“VoyageNumber” is the identifier for the entity.
Now I can insert a new voyage just fine with:
MongoCollection<Voyage> mongoVoyages = context.MyDB.GetCollection<Voyage>("Voyages");
mongoVoyages.Insert<Voyage>(voyage);
I can retrieve one Voyage via:
MongoCollection mongoVoyages = context.MyDB.GetCollection("Voyages");
BsonDocument result = mongoVoyages.FindOneAs<BsonDocument>();
BsonDocument sched = result["Schedule"].AsBsonDocument;
DateTime start = sched["StartDate"].AsDateTime;
//etc...
Now of course I’d like to search a voyage by Id. How can I achieve this with the mappings shown above? I tried something like this and failed:
Query.EQ("VoyageNumber", someStringID)
I’m using the official C# driver 1.0.
With above classes registration you will have document like this in mongodb:
So if you want get
VoyagebyVoyageNumberId you should use following query:Note: You no need
BsonClassMap.RegisterClassMapfor class if you map all fileds because it will be serialized by default without any registration. Also you can do custom serialization using attributes like[BsonId],[BsonIgnore]. For more details check documentation or ask another question ;).From documentation: