使用regex mongo c#在列表中查找
本文关键字:列表 查找 regex mongo 使用 | 更新日期: 2023-09-27 18:26:37
我可以用一个函数来实现这一点吗?或者用一个查询的更简短的方式来实现,而不是用那个?我正在尝试使用regex获取电子邮件,但我需要检查列表中的每封电子邮件。
public ObjectId? GetEntityIdByEmail(string email)
{
var projection = Builders<Entity>.Projection.Include(x=>x._id);
var filter = Builders<Entity>.Filter.Regex("Email", new BsonRegularExpression(new Regex(email, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)));
var id = _entitiesStorage.SelectAsSingleOrDefault(filter,projection);
if (id == null)
return null;
return (ObjectId)id["_id"];
}
public List<ObjectId> GetEntitiesIdsByEmail(IList<string> emails)
{
var result = new List<ObjectId>();
foreach (var email in emails)
{
var id = GetEntityIdByEmail(email);
if (id != null)
result.Add(id.Value);
}
return result;
}
您可以扩展正则表达式查询
public async Task<List<ObjectId>> GetEntitiesIdsByEmail(IList<string> emails)
{
var regexFilter = "(" + string.Join("|", emails) + ")";
var projection = Builders<Entity>.Projection.Include(x => x.Id);
var filter = Builders<Entity>.Filter.Regex("Email",
new BsonRegularExpression(new Regex(regexFilter, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)));
var entities = await GetCollection().Find(filter).Project(projection).ToListAsync();
return entities.Select(x=>x["_id"].AsObjectId).ToList();
}