Binding C# Class Instance to MongoDB Collection

I have a C#/WPF application has has been developed with several class instances. Of course these are not persistent. I would like to bind the class instances to MongoDB collections for persistence and to enable backups.
How can I bind a class instance to a MongoDB collection so as the content of the class instance changes the changes will be reflected in the MongoDB collection?


Have a look at this example that save C # class instance and retrieve it.


Thanks for the sample code. I am looking for a way to bind a class to a collection. The code has been written and I don’t want to rewrite it :slight_smile:

I want to continue to read and write the class instance and have it bound to the collection.


You need to decide when to write the instance in MongoDB.
I don’t recommand to write every modification automatically.
It’s possible but this is not a MongoDB feature, this is a C# feature.
Read the instance on screen opening.
Write it on screen closing for example.

Here are 3 strategies to use class that you can’t adapt with MongoDB.

  1. you can use inherence to add an id field

public class theClassICantChange
public string Name;


public class mdbWrapper : theClassICantChange
public ObjectId id;

and then use the wrapper class for db insert/query

  1. you can serialize “manually”

BsonDocument doc = o2.ToBsonDocument();
the insert and query BsonDocument

Look at examples 3 and 1

  1. More complex, you can write your own serializer


Thanks for the additional information.

I have implemented a process where I first DropCollection and immediately InsertMany attempting to “replace” the collection with the class instance.

This works most of the time but because I have multiple clients accessing the database, occasionally the collection gets dropped and not created as this process is not collection atomic.

I tried to use a transaction to update the collection with …

using (var session = await client.StartSessionAsync())

… but I get an error that says you can’t do a transaction on a single server instance and I cannot change the database configuration :frowning:

What do want to achieve ? Some sort of synchronization between clients?

Dropping the collection is not recommanded.
await collection.DeleteManyAsync(_ => true);
to delete all records.