admin管理员组

文章数量:1320588

I'm trying to test out mongodb - ultimately using change streams. For that, I need to use a replica set

I'm using this docker-compose file to start docker with a replica set

version: "3.8"

services:
  mongo1:
    image: mongo:8.0
    command: ["--replSet", "rs0", "--bind_ip_all", "--port", "27017"]
    ports:
      - 27017:27017
    extra_hosts:
      - "host.docker.internal:host-gateway"
    volumes:
      - "mongo1_data:/data/db"
      - "mongo1_config:/data/configdb"

volumes:
  mongo1_data:
  mongo1_config:

If I connect to mongo using mongosh localhost:27017 it works.

However, if I try to connect using the mongodb c# driver with a very simple app, I get a timeout error. The app is just running in rider / using dotnet run from terminal

using MongoDB.Bson;
using MongoDB.Driver;

class Program
{
    static async Task Main(string[] args)
    {
        const string connectionString = "mongodb://localhost:27017";
        const string databaseName = "mydatabse";
        const string collectionName = "test";

        var client = new MongoClient(connectionString);

        try
        {
            var databases = client.ListDatabaseNames().ToList();
            Console.WriteLine("Connected to MongoDB!");
            Console.WriteLine("Databases:");
            databases.ForEach(Console.WriteLine);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Error: A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode : Primary } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", Type : "Unknown", State : "Connected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/localhost:27017" }", EndPoint: "Unspecified/localhost:27017", ReasonChanged: "Heartbeat", State: "Connected", ServerVersion: 8.0.0, TopologyVersion: { "processId" : { "$oid" : "678ae1e581b6a4e5cd57e0ed" }, "counter" : 0 }, Type: "ReplicaSetGhost", WireVersionRange: "[0, 25]", LastHeartbeatTimestamp: "2025-01-17T23:04:58.6182020Z", LastUpdateTimestamp: "2025-01-17T23:04:58.6182020Z" }] }.

I use OrbStack for docker - not sure if that's relevant.

本文标签: