MongoDb FindAsync Cursor with Filter always returning null

11,532

Solution 1

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

Solution 2

the basic, asynchronous form

   data= await collectin.FindAsync(new BsonDocument {{ "_id", new ObjectId(id) } }).Result.FirstAsync();
Share:
11,532
Hary
Author by

Hary

Techno freak...

Updated on June 14, 2022

Comments

  • Hary
    Hary almost 2 years

    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
    }
    
  • Neo
    Neo over 4 years
    In C# 8.0, if the method returns an IEnumerable, you can use yield return cursor.Current in the while loop. Much cleaner and properly async.
  • Hardik Masalawala
    Hardik Masalawala over 2 years
    Thanks It is what I was finding from last 2 days