Getting a single object from mongodb in C#

久未见 提交于 2019-12-01 07:33:04

Yes, there is.

First of all don't use FindAsync, use Find instead. On the IFindFluent result use the SingleAsync extension method and await the returned task inside an async method:

async Task MainAsync()
{
    IMongoCollection<ApplicationUser> userCollection = ...;

    var applicationUser = await userCollection.Find(_ => _.Id == inputId).SingleAsync();
}

The new driver uses async-await exclusively. Don't block on it by using Task.Result.

You should limit your query before executing, otherwise you will first find all results and then only read one of it.

You could either specify the limit using FindOptions in FindAsync, or use the fluent syntax to limit the query before executing it:

var results = await userCollection.Find(x => x.Id == inputId).Limit(1).ToListAsync();
ApplicationUser singleResult = results.FirstOrDefault();

The result from ToListAsync will be a list but since you limited the number of results to 1, that list will only have a single result which you can access using Linq.

I could not get the method:

coll.Find(_ => _.Id == inputId).SingleAsync();

To work as I was getting the error

InvalidOperationException: Sequence contains more than one element c#

So I ended up using .FirstOrDefault()

Example:

public FooClass GetFirstFooDocument(string templatename)
        {
            var coll = db.GetCollection<FooClass>("foo");
            FooClass foo = coll.Find(_ => _.TemplateName == templatename).FirstOrDefault();
            return foo; 
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!