Search code examples
mongodbmongodb-.net-driver

MongoDB C# Driver tailable cursor on oplog.rs


I am trying to write an oplog watcher using the MongoDB C# Driver that resembles the one implemented in Java Here.

So far i've managed to write:

public static void Read()
{
    const string connectionString = "mongodb://127.0.0.1:27017,127.0.0.1:27018/?replicaSet=rs0";
    MongoClient mongoClient = new MongoClient(connectionString);

    MongoDatabase local = mongoClient.GetServer().GetDatabase("local");
    MongoCollection opLog = local.GetCollection("oplog.$main");
    BsonValue lastId = BsonMinKey.Value;
    while (true)
    {
        var query = Query.GT("_id", lastId);
        var cursor = opLog.FindAs<BsonDocument>(query)
                    .SetFlags(
                        QueryFlags.AwaitData |
                        QueryFlags.TailableCursor |
                        QueryFlags.NoCursorTimeout)
                    .SetSortOrder(SortBy.Ascending("$natural"));
        using (var enumerator = (MongoCursorEnumerator<BsonDocument>)cursor.GetEnumerator())
        {
            while (true)
            {
            // I get a "tailable cursor requested on non capped collection" Exception
                if (enumerator.MoveNext())
                {
                    var document = enumerator.Current;
                    lastId = document["_id"];
                }
                else
                {
                    if (enumerator.IsDead)
                    {
                        break;
                    }
                    if (!enumerator.IsServerAwaitCapable)
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(100));
                    }
                }
            }
        }
    }
}

I've created the oplog on the server and succesfully queried it from the mongo command line using the instructions found here, but i cant figure out why the exception says it is not capped.


Solution

  • If you are using and have set up a replicaset, you have an oplog.

    To query the oplog, you would use the database 'local' as you do.

    then change

    local.GetCollection("oplog.$main");
    

    to

    local.GetCollection("oplog.rs");