How to parse a simple class to Bson and to a MongoDB collection

2.8k views Asked by At

I'm brand new to MongoDB in C#.

I have created a very simple class which I would like to automatically insert into a collection.

How do I do that, if I don't want to map everything manually?

public class DummyClass
{
    [BsonId]        
    public int Id { set; get; }

    [BsonElement("first")]
    public string First { set { _name = value; } }

    [BsonConstructor]
    public DummyClass()
    {
        Id = 2;
        First = "1";
    }
}

I had hoped I could do something like this:

_dbClient = new MongoClient();
_database = _dbClient.GetDatabase("testDB");
_collection = _database.GetCollection<BsonDocument>("Collection");

var doc = BsonDocument.Create(dummy);
_collection.InsertOneAsync(doc);

But it's no good. I get the exception:

System.ArgumentException : .NET type DummyClass cannot be mapped to BsonType.Document. 
Parameter name: value

Any suggestions?

And I really don't want to do:

{
    {"Id", "2"},
    {"First", "1"},
}

EDIT: I forgot this small line:

BsonClassMap.RegisterClassMap<DummyClass>();

It does wonders.

2

There are 2 answers

0
rnofenko On BEST ANSWER

It makes sense to use BsonDocument when fields in collections don't match properties in your model class. Otherwise you should create collection mapped to your class.

_collection = _database.GetCollection<DummyClass>("Collection");
await _collection.InsertOneAsync(doc);

And don't forget about async/await methods in MongoDB.Driver.

0
davcup On

You can use ToBsonDocument()

_collection.InsertOneAsync(doc.ToBsonDocument())