我需要使用用户输入从集合中检索一个 BsonDocument。我已经找到了一种简单的方法来做到这一点:
var filter = Builders<BsonDocument>.Filter.Eq("name", name);
var doc = await myCollection.Find(filter).SingleAsync();
这工作正常,但是当没有匹配时,它会System.InvalidOperationException在SingleAsync方法中抛出一个:
Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at MongoDB.Driver.IAsyncCursorExtensions.SingleAsync[TDocument](IAsyncCursor`1 cursor, CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.SingleAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
at MyProgram.Main.Test() in D:\MyProgram\Main.cs:line 22
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ThreadPoolWorkQueue.Dispatch()
我想我可以在每次发生这种异常时捕获它,但这是正确的方法吗?我也可以使用它来检查是否存在AnyAsync,但这将涉及执行两个单独的查询,这可能会损害数据库性能。
这样做的正确方法是什么?
皈依舞
相关分类