I'm trying to write some data to Mongo DB that is hosted on Azure. For this I've created a Cosmos DB account with the API "Azure Cosmos DB for MongoDB API".
To write my data I use this code using .NET Framework 4.7.2 and C#.
string connectionString = "mongodb://<username>:<password>@<host>:<port>/?ssl=true&replicaSet=globaldb&appname=@<region>";
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
settings.SslSettings = new SslSettings()
{
EnabledSslProtocols = SslProtocols.Tls12
};
MongoClient mongoClient = new MongoClient(settings);
IMongoDatabase mongoDatabase = mongoClient.GetDatabase(DatabaseId); // `DatabaseId` is a `string`.
IMongoCollection<TEntity> mongoCollection = mongoDatabase.GetCollection<TEntity>(CollectionId); // `CollectionId` is a `string`.
IEnumerable<WriteModel<TEntity>> entitiesToInsert = entities.Select(entity => new InsertOneModel<TEntity>(entity)); // `entities` is an `IEnumerable<TEntity>` where `TEntity` is `class`.
await mongoCollection.BulkWriteAsync(entitiesToInsert); // → Error on this line.
But on the last line, I've always this exception. It happens not occasionally and retrying fails too. The database and collection name both exists.
TimeoutException
: A timeout occured after 30000ms selecting a server usingCompositeServerSelector
.
MongoConnectionException
: An exception occurred while opening a connection to the server.
SocketException
: No connection could be made because the target machine actively refused it x.x.x.x:10255
The firewall is configured to allow access from all networks.
Why happens this error and how could I solve this?
Update: By adding the database to the connection string and removing the replicaSet
and appname
, doesn't solve my problem.
mongodb://<username>:<password>@<host>:<port>/<database>?ssl=true