Check if the MongoDB Collection is Limited to the .NET 2.0 Driver

With the old legacy .NET MongoDB driver, I used the following to create a limited collection if it does not already exist (not bulletproof, but stopped us by accident with unassigned collections several times):

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));
}

How can I do the same with the new version of the .NET driver MongoDB 2.0? Ideally, I would like to adhere to the same behavior as above, but it would be enough to throw an exception. Although it is possible to create a limited collection with CreateCollectionAsync, it is not possible to check if the existing collection is closed.

db.collection.isCapped(), , .NET API. - capped, , .

+4
1

, MongoDB.Driver 2.0 isCapped.

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;
}
+5

All Articles