我正在尝试使用类似于在 Java Here中实现的 MongoDB C# 驱动程序编写一个 oplog 观察程序。
到目前为止,我已经设法写了:
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));
}
}
}
}
}
}
我已经在服务器上创建了 oplog 并使用此处找到的说明从 mongo 命令行成功查询了它,但我无法弄清楚为什么异常说它没有上限。