1

I am trying to create a helper class for interacting with MongoDb in C# 4.0. I've been reading some of the documentation on serializing to Bson, etc. but am a little lost. What I have is a generic MongoHelper class with and Add(T objectToAdd), Delete(T objectToDelete) and Update(T objectToUpdate) method. The constructor takes in the server, db and collection info.

I am having trouble however, trying to serialize from T. I ignorantly tried something like this:

BsonClassMap.RegisterClassMap().ToBsonDocument();

I'm really lost on such a simple thing. Please help!

1 Answer 1

3

You don't have to serialize your objects. The driver does that for you. If you are working with C# classes just make sure your class has a public no-argument constructor and that the values you want serialized are exposed as public properties. Classes like that are handled automatically. Alternatively, you might choose to work at a lower level with BsonDocuments, but they also are serialized for you automatically.

All you need to do to save an object of class C to the database is:

var server = MongoServer.Create("mongodb://localhost/?safe=true");
var database = server.GetDatabase("test");
var collection = database.GetCollection<C>("test");
var c = new C();
// initialize c
collection.Insert(c);

That's all there is to it. To read it back you just write:

c = collection.FindOne();

although typically you would write a query as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! So much easier! Using generics adds a bit of complexity but still way easier than SQL server. Thank you!
Actually you can use MongoDB.Dynamic to abstract you MongoDB Collections and use it as you helper class. assembla.com/spaces/mongodb-dynamic/wiki

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.