1

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;
}

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.