Search code examples
c#mongodbmongodb-.net-driver

MongoDb FindAsync Cursor with Filter always returning null


I use the below code to filter collection by Field name. But result.Current is always null whereas the data exists in MongoCollection. Any Ideas?

Code

public async Task<IdentityUser> FindByNameAsync(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("Null or empty argument: userName");
            }

            var filter = Builders<IdentityUser>.Filter.Eq("UserName", userName);
            var result = await _collection.FindAsync(filter);

            if (result != null && result.Current != null && result.Current.Count() == 1)
            {
                return result.Current.Single();
            }

            return null;
        }

Mongo Document

{
    "_id": {
        "$oid": "558acd1768869a0f6c45ab78"
    },
    "CreatedBy": 0,
    "UpdatedBy": 0,
    "CreatedTime": {
        "$date": "2015-06-24T15:30:28.336Z"
    },
    "UpdatedTime": {
        "$date": "0001-01-03T00:00:00.000Z"
    },
    "UserName": "test",
    "Email": null,
    "EmailConfirmed": false,
    "PasswordHash": "test",
    "SecurityStamp": null,
    "PhoneNumber": null,
    "PhoneNumberConfirmed": false,
    "TwoFactorEnabled": false,
    "LockoutEndDateUtc": null,
    "LockoutEnabled": false,
    "AccessFailedCount": 0
}

Solution

  • For simple queries (your case) you should use next:

    var user = await collection.Find(x => x.UserName != userName).FirstAsync();
    

    You tried to use cursor. It makes sense when a query can return a lot of data, in this case cursor is used next way:

    var cursor = await collection.FindAsync(x => x.UserName != userName);
    while (await cursor.MoveNextAsync())
    {
          var listOfUsers = cursor.Current;
    }
    

    PS: Find - returns result, FindAsync - returns cursor