Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter with regex MongoDB C# driver

Tags:

c#

mongodb

filter

I am trying to match the fields of originalEmail with a mail address like [email protected], but no matter, case sensitive means to also find [email protected] fields.

public ObjectId? GetEntityIdByOriginalEmail(string originalEmail)
{
    FilterDefinition<Entity> filter = "{ x : { $regex : /" + originalEmail + "//i } }";
    var entity = _entitiesStorage.GetSingleOrDefault(filter);

    if (entity == null)
        return null;

    return entity._id;
}

This didn't work for me. Why?

like image 286
User9898 Avatar asked Dec 09 '15 17:12

User9898


1 Answers

You can use Builders.Filter.Regex.

public async Task<Entity> GetEntityIdByOriginalEmail(string originalEmail)
{
    var collection = GetCollection();
    var filter = Builders<Entity>.Filter.Regex("x", new BsonRegularExpression(originalEmail, "i"));
    return await collection.Find(filter).FirstOrDefaultAsync();
}
like image 93
rnofenko Avatar answered Sep 19 '22 11:09

rnofenko