5

Mongodb has a FindAsync and a Find. I get how that could potentially be useful if you were going to pass around the cursor, but I don't totally understand how it works with their own ToListAsync. Here are two queries. Is one better than the other performance wise? Specifically with queries of say 200-1000 documents.

public async Task<List<MongoUser>> GetUsersAsync(IEnumerable<Guid> userGuids)
{
    var filter = Builders<MongoUser>.Filter.In(u => u.Guid, userGuids);
    var resultCursor = await Db.GetCollection<MongoUser>("Users").FindAsync(filter);
    var users = await resultCursor.ToListAsync();
    return users;
}

public async Task<List<MongoUser>> GetUsersAsync2(IEnumerable<Guid> userGuids)
{
    var filter = Builders<MongoUser>.Filter.In(u => u.Guid, userGuids);
    var users = await Db.GetCollection<MongoUser>("Users").Find(filter).ToListAsync();
    return users;
}

This question is similar for reference

However, I don't think the answer is clear in my question. Through the comments the asked said "I am loading exactly one document either way" and the reply was "For one document Find looks better because you doesn't work with cursor." I believe this ended the thread for that question.

The answer is confusing because he says both "Find and FindAsync both allows to build asynchronous query with the same performance" and "FindAsync returns cursor which doesn't load all documents at once and provides you interface to retrieve documents one by one from DB cursor. It's helpful in case when query result is huge." Perhaps he is also referring to small queries.

I'm hoping to understand if MongoDb performs well with just the ToListAsync() by not blocking the thread until the whole command is done, or if it is necessary to use FindAsync() to force MongoDb to release the thread while it is building the query or whatever Find() by itself does.

bgraham
  • 1,939
  • 1
  • 10
  • 17

0 Answers0