我使用以下代码按字段名称过滤集合。但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
}
答案 0 :(得分:5)
对于简单查询(您的情况),您应该使用下一个:
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
- 返回游标