Reputation: 251
can i do this in one function or in more short way of one query instead of that? i am trying to get email with a regex but i need to check each email in the 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;
}
Upvotes: 1
Views: 2175
Reputation: 9533
You can extend you regex query
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();
}
Upvotes: 1