MongoDB.Driver.MongoConnectionException: An exception occurred while sending a message to the server

I got below exception while try to update data in mongodb. Please help me to fix this issue.

When I look in my logs I see lot of error messages just like the one below where the driver is getting a socket error when connecting to mongo. The site is still up and this error doesn’t happen on every request, nor does it happen on one operation that should take longer.

The version I have used C# driver : “2.10.2” and Azure Cosmos version :3.6".

MongoDB.Driver.MongoConnectionException: An exception occurred while sending a message to the server. ---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Security._SslStream.StartWriting(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at MongoDB.Driver.Core.Misc.StreamExtensionMethods.WriteBytes(Stream stream, IByteBuffer buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Connections.BinaryConnection.SendBuffer(IByteBuffer buffer, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.SendBuffer(IByteBuffer buffer, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Connections.BinaryConnection.SendMessages(IEnumerable`1 messages, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.AcquiredConnection.SendMessages(IEnumerable`1 messages, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Connections.ConnectionExtensions.SendMessage(IConnection connection, RequestMessage message, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocol[TResult](IWireProtocol`1 protocol, ICoreSession session, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Servers.Server.ServerChannel.Command[TResult](ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, IEnumerable`1 commandPayloads, IElementNameValidator commandValidator, BsonDocument additionalOptions, Action`1 postWriteAction, CommandResponseHandling responseHandling, IBsonSerializer`1 resultSerializer, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.RetryableWriteCommandOperationBase.ExecuteAttempt(RetryableWriteContext context, Int32 attempt, Nullable`1 transactionNumber, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.RetryableWriteOperationExecutor.Execute[TResult](IRetryableWriteOperation`1 operation, RetryableWriteContext context, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.ExecuteBatches(RetryableWriteContext context, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.Execute(RetryableWriteContext context, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.Execute(IWriteBinding binding, CancellationToken cancellationToken)
   at MongoDB.Driver.OperationExecutor.ExecuteWriteOperation[TResult](IWriteBinding binding, IWriteOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.ExecuteWriteOperation[TResult](IClientSessionHandle session, IWriteOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.<>c__DisplayClass23_0.<BulkWrite>b__0(IClientSessionHandle session)
   at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionBase`1.<>c__DisplayClass92_0.<UpdateMany>b__0(IEnumerable`1 requests, BulkWriteOptions bulkWriteOptions)
   at MongoDB.Driver.MongoCollectionBase`1.UpdateMany(FilterDefinition`1 filter, UpdateDefinition`1 update, UpdateOptions options, Func`3 bulkWrite)
   at MongoDB.Driver.MongoCollectionBase`1.UpdateMany(FilterDefinition`1 filter, UpdateDefinition`1 update, UpdateOptions options, CancellationToken cancellationToken)
   at Sensiple.Tryvium.Data.MongoDB.CommonConnector.Update(String schemaName, String dataFilter, String data, String logSource) 

Code that causes issue,

var _collection = Db.GetCollection<BsonDocument>(schemaName); 

BsonDocument bsonDocument = new BsonDocument(BsonSerializer.Deserialize<BsonDocument>(dataFilter)); 

var updatedResult = _collection.UpdateMany(bsonDocument, BsonDocument.Parse("{$set: " + BsonSerializer.Deserialize<BsonDocument>(data) + "}"));

Hi,

The version I have used C# driver : “2.10.2” and Azure Cosmos version :3.6".

It appears that you are trying to connect to Azure Cosmos DB using the official MongoDB dotnet driver. Is this correct?

If yes, then unfortunately this configuration is not supported since Cosmos DB is a Microsoft product that provides MongoDB compatibility, and thus it may time to time see some incompatibilities with official MongoDB drivers, which are designed for use with the official MongoDB server.

Could you try the code on an official MongoDB server (e.g. a free MongoDB Atlas shared instance for testing purposes) and see if the error persists? If not, then you may want to contact Microsoft support regarding this issue.

Best regards,
Kevin

1 Like

I’ve had the exact same issue (using exact same driver version 2.10.2), and it started exactly after I’ve upgraded from Cosmos 3.2 to 3.6 (also happens with 4.0) and the issue was solved by forcing TLS 1.2

var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.SslSettings = new SslSettings()
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
};
return new MongoClient(settings);

2 Likes

@Ricardo_Drizin, Hitting a similar issue, Azure CosmosDB 4.0 and MongoDB.Driver 2.18 and have set TLS1.2 as in your example. Your sample is also very similar to the suggested code sample in Azure. Just curios if you have any thoughts