带有Filter的MongoDb FindAsync游标始终返回null

本文关键字:返回 null 游标 FindAsync Filter MongoDb 带有 | 更新日期: 2023-09-27 17:59:21

我使用以下代码按字段名称筛选集合。但是result.Current总是null,而数据存在于MongoCollection中。有什么想法吗?

代码

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文档

{
    "_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
}

带有Filter的MongoDb FindAsync游标始终返回null

对于简单的查询(您的案例),您应该使用下一个:

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

您尝试使用光标。当一个查询可以返回大量数据时,这是有意义的,在这种情况下,光标被用于下一种方式:

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

PS:Find-返回结果,FindAsync-返回光标

基本的异步形式

   data= await collectin.FindAsync(new BsonDocument {{ "_id", new ObjectId(id) } }).Result.FirstAsync();