我正在更新代码以使用MongoDB新的异步API.
I'm updating my code to use MongoDB new async API.
我的用法之一是使用:
return Database.GetCollection("collectionName").GetStats().DataSize是否有像传统API中的MongoCollection.GetStats()一样从IMongoCollection获取CollectionStatsResult对象的方法? 我现在唯一看到的选择是获取一个Json文档并对其进行解析:
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"]);推荐答案
异步API中没有强类型方法.收集统计数据的结果继续改变形状,删除了某些字段,添加了其他字段等.将其保留为强类型并不明智.手动运行它现在所要做的就是正确的方法.
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'}");