问题
I'm updating my code to use MongoDB new async API.
One of my usages is to get the data size of the collection using :
return Database.GetCollection("collectionName").GetStats().DataSize
Is there any way to get a CollectionStatsResult
object from IMongoCollection
like MongoCollection.GetStats()
did in the legacy API?
The only option I see for now is to get a Json document and parse it :
var jsonCommand = new JsonCommand<BsonDocument>("{collstats : \"collectionName\"}");
var jsonDocument = await Database.RunCommandAsync(jsonCommand);
return Convert.ToInt64(jsonDocument["size"]);
回答1:
There is not a strongly-type way in the async API. The results of collection stats continue to change shape, removed certain fields, added others, etc... It wasn't prudent to keep this as a strong-type. What you are doing now by running it manually is the correct way to do it.
If you'd like a strong-type result, you can define a simple class containing the portions you'd like and pass it along.
[BsonIgnoreExtraElements]
class SizeResult
{
[BsonElement("size")]
public long Size { get; set; }
}
var result = await database.RunCommandAsync<SizeResult>("{collstats: 'collectionName'}");
来源:https://stackoverflow.com/questions/33331344/imongocollection-stats