[英]Getting a single object from mongodb in C#
我找到了一段代碼,它使用這樣的 MongoDB 驅動程序從集合中獲取單個對象......這不可能是對的,是嗎? 有沒有更好的方法來獲得這個?
IMongoCollection<ApplicationUser> userCollection;
....
userCollection.FindAsync(x => x.Id == inputId).Result.ToListAsync().Result.Single();
就在這里。
首先不要使用FindAsync
,而是使用Find
。 在IFindFluent
結果上,使用SingleAsync
擴展方法並在異步方法中等待返回的任務:
async Task MainAsync()
{
IMongoCollection<ApplicationUser> userCollection = ...;
var applicationUser = await userCollection.Find(_ => _.Id == inputId).SingleAsync();
}
新驅動程序專門使用 async-await。 不要使用Task.Result
阻止它。
您應該在執行之前限制您的查詢,否則您將首先找到所有結果,然后只讀取其中一個。
您可以在FindAsync
使用FindOptions
指定限制,或者在執行查詢之前使用流暢的語法來限制查詢:
var results = await userCollection.Find(x => x.Id == inputId).Limit(1).ToListAsync();
ApplicationUser singleResult = results.FirstOrDefault();
ToListAsync
的結果將是一個列表,但由於您將結果數量限制為 1,該列表將只有一個您可以使用 Linq 訪問的結果。
在較新版本的 MongoDB Find() 中已棄用,因此您可以使用
collection.FindSync(o => o.Id == myId).Single()
或者
collection.FindAsync(o => o.Id == myId).Result.Single()
您還可以使用SingleOrDefault()
,如果未找到匹配項,則返回 null 而不是拋出異常。
我無法獲得方法:
coll.Find(_ => _.Id == inputId).SingleAsync();
在我收到錯誤時工作
InvalidOperationException: Sequence contains more than one element c#
所以我最終使用了.FirstOrDefault()
例子:
public FooClass GetFirstFooDocument(string templatename)
{
var coll = db.GetCollection<FooClass>("foo");
FooClass foo = coll.Find(_ => _.TemplateName == templatename).FirstOrDefault();
return foo;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.