C# MongoDB driver calculating data size is wrong

I am using MongoDB C# driver “2.13.0” with MongoDB.Bson version “2.13.0” to connect and insert and retrieve data from MongoDB.

Now as per official website the document limit is 16 MB https://www.mongodb.com/docs/manual/reference/limits/

But when I am trying to insert data which is in KB’s if I put it in Notepad but the code is complaining the size limit.

System.FormatException: Size 16948171 is larger than MaxDocumentSize 16793600

But when I am using file to insert from MongoDB shell using command it’s working fine. Means it’s not complaining for the size there. Written first delete and then insert query.

Thanks for reporting this. I attempted to reproduce it but was unable to. According to my attempt the calculation is spot on.

This is the test I wrote:

[Fact]
public void InsertOne_with_largest_possible_document_should_work()
{
    var collection = CreateCollection(); // returns IMongoCollection<C>

    var documentWithEmptyString = new C { Id = 1, S = "" };
    var documentOverhead = documentWithEmptyString.ToBson().Length; // equals 22 bytes

    var maxDocumentSize = 16777216; // 16 MB
    var maxStringSize = maxDocumentSize - documentOverhead; // equals 16777194 chars
    var largestPossibleDocument = new C { Id = 1, S = new string('x', maxStringSize) };
    largestPossibleDocument.ToBson().Length.Should().Be(maxDocumentSize);

    collection.InsertOne(largestPossibleDocument);
    var roundTrippedDocument = collection.FindSync("{}").Single();
    roundTrippedDocument.ToBson().Length.Should().Be(maxDocumentSize);

    var documentSizeOnServer = collection
        .Aggregate()
        .AppendStage<BsonDocument>("{ $project : { documentSize : { $bsonSize : '$$ROOT' }, _id : 0 } }")
        .Single();
    documentSizeOnServer["documentSize"].AsInt32.Should().Be(maxDocumentSize);
}

This is the class definition of C:

private class C
{
    public int Id { get; set; }
    public string S { get; set; }
}

I did just notice that in your error message the MaxDocumentSize is 16793600, whereas I was expecting 16777216.

So perhaps my test to reproduce does not match what you are doing.

Can you provide more information? Ideally you could provide us with a small standalone program that minimally reproduces the problem.