Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a single object from mongodb in C#

I've picked up a piece of code that is using the MongoDB driver like this to get a single object from a collection...this can't be right, can it? Is there a better way of getting this?

IMongoCollection<ApplicationUser> userCollection;
....
userCollection.FindAsync(x => x.Id == inputId).Result.ToListAsync().Result.Single();
like image 561
Paul Avatar asked Jul 01 '15 20:07

Paul


2 Answers

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.

like image 60
poke Avatar answered Sep 21 '22 14:09

poke


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.

like image 41
i3arnon Avatar answered Sep 19 '22 14:09

i3arnon