Error Inserting Records into a MongoDb Database

May 29, 2021

In my recent posts I’ve been trying to learn a little about MongoDB, and the API. Whilst trying to insert data into a MongoDB database, I got an error; and, since I couldn’t really find anything about it on the internet, I thought I’d add something.

Here’s the code that I initially (and incorrectly) tried to use to insert a record:



            var newData = new MyData()
            {
                SomeDate = myDate,
                Text = "hello"
            };
            var document = BsonDocument.Create(newData);

            var collection = \_db.GetCollection<BsonDocument>("testcollection");
            await collection.InsertOneAsync(document);

            return newData.Id.ToString();


If you execute the code above, you’ll get the following error:

System.ArgumentException: ‘.NET type MyApp.Entities.MyData cannot be mapped to BsonType.Document. ’

In fact, the issue is caused because you need to convert the data into a BSON document first; like so:



            var newData = new MyData()
            {
                SomeDate = myDate,
                Text = "hello"
            };
            var bson = newData.ToBsonDocument();
            var document = BsonDocument.Create(bson);            

            var collection = \_db.GetCollection<BsonDocument>("testcollection");
            await collection.InsertOneAsync(document);

            return newData.Id.ToString();




Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024