简体   繁体   中英

use regex mongo c# to find in list

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM