使用正则表达式 mongo c# 在列表中查找
use regex mongo c# to find in list
我可以在一个函数中执行此操作,还是可以通过一个查询的更短方式来执行此操作?
我正在尝试使用正则表达式接收电子邮件,但我需要检查列表中的每封电子邮件。
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();
}
我可以在一个函数中执行此操作,还是可以通过一个查询的更短方式来执行此操作? 我正在尝试使用正则表达式接收电子邮件,但我需要检查列表中的每封电子邮件。
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();
}