检查MongoDB集合是否受.NET 2.0驱动程序的限制 [英] Check to see if a MongoDB collection is capped with the .NET 2.0 driver

查看:62
本文介绍了检查MongoDB集合是否受.NET 2.0驱动程序的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用现在遗留的.NET MongoDB驱动程序,我曾经使用以下命令创建一个有上限的集合(如果尚不存在)(不是防弹的,但是它使我们在某些情况下意外地使用了无上限的集合):

With the now legacy .NET MongoDB driver I used to use the following to create a capped collection if it didn't already exist (not bulletproof, but it stopped us accidentally using uncapped collections on several occasions):

private MongoCollection GetCappedCollection(string collectionName, long maxSize)
{
    if (!this.database.CollectionExists(collectionName))
        CreateCollection(collectionName, maxSize);

    MongoCollection<BsonDocument> cappedCollection = this.database.GetCollection(collectionName);
    if (!cappedCollection.IsCapped())
        throw new MongoException(
            string.Format("A capped collection is required but the \"{0}\" collection is not capped.", collectionName));

    return cappedCollection;
}

private void CreateCappedCollection(string collectionName, long maxSize)
{
    this.database.CreateCollection(collectionName,
                                   CollectionOptions
                                      .SetCapped(true)
                                      .SetMaxSize(maxSize));
}

如何对新的2.0版.NET MongoDB驱动程序执行相同的操作?理想情况下,我希望保持与上述相同的行为,但是抛出异常就足够了.尽管可以使用CreateCollectionAsync创建一个有上限的集合,但是似乎无法检查现有集合是否有上限.

How can I do the same with the new 2.0 version of the .NET MongoDB driver? Ideally I'd like to keep the same behavior as above but it would be good enough to throw the exception. While it's possible to create a capped collection using CreateCollectionAsync it doesn't seem possible to check to see if an existing collection is capped.

该外壳具有db.collection.isCapped(),但是在.NET API中找不到等效项.另一种方法是获取集合的统计信息,并检查capped标志,但我也看不到该怎么做.

The shell has db.collection.isCapped() but there is no equivalent that I can find in the .NET API. Another approach would be to get the stats for a collection and check for the capped flag, but I can't see how to do that either.

推荐答案

是的,MongoDB.Driver 2.0中没有isCapped.但是您可以从集合统计信息中获取它

Yes, There isn't isCapped in MongoDB.Driver 2.0. But you can get it from collection stats

public async Task<bool> IsCollectionCapped(string collectionName)
{
    var command = new BsonDocumentCommand<BsonDocument>(new BsonDocument
    {
        {"collstats", collectionName}
    });

    var stats = await GetDatabase().RunCommandAsync(command);
    return stats["capped"].AsBoolean;
}

这篇关于检查MongoDB集合是否受.NET 2.0驱动程序的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆