c#

mongodb

mongodb-.net-driver

mongodb-csharp-2.0

i am using official mongodb c# driver. i want to query mongodb simliar to SQL Like something like db.users.find({name:/Joe/} in c# driver

Solution 1

c# query will looks like:

Query.Matches("name", BsonRegularExpression.Create(new Regex("Joe")));

Update:

As per @RoberStam suggestion, there is more simple way to do this:

Query.Matches("name", "Joe") 

Solution 2

For the c# driver 2.1 (MongoDB 3.0)

var collection = database.GetCollection<BsonDocument>("<<name of the collection>>");

var filter = Builders<BsonDocument>.Filter.Regex("name", new BsonRegularExpression("Joe"));

var result = await collection.Find(filter).ToListAsync();

For the c# driver 2.2 (MongoDB 3.0)

var filter = new BsonDocument { { parameterName, new BsonDocument { { "$regex", value }, { "$options", "i"} } } }

var result = collection.Find(filter).ToList();

Solution 3

MongoDB C# driver has a BsonRegex type that you can use.

Regex is the closest you will get to the SQL LIKE statement.

Note that prefixed Regexes can use indexes: /^Joe/ will use an index, /Joe/ will not.

Solution 4

Suppose I need to search the value of variable 'textToSearch' from a property of Mongodb documents.

Example: We have to search manager in all the records where JobModel.Title contains manager. That is textToSearch=manager from the records. ( textToSearch is a string type. I have added some Regexs at the end of my answer. To cover textToSearch contains, textToSearch starts with and few more scenarios)

Equivalent C# Code:

Note: I have also shown how you can append to your existing filter, ignore it if not required.

var mongoBuilder = Builders<BsonDocument>.Filter;
var filter = mongoBuilder.Eq(y => y.JobModel.Category, "full time");

if (!string.IsNullOrEmpty(textToSearch))
{
    textToSearch = "/.*" + textToSearch + ".*/i"; // this regex will search all the records which contains textToSearch and ignores case
    filter = filter & mongoBuilder.Regex(y => y.JobModel.Title, new BsonRegularExpression(textToSearch));
}                

Equivalent Mongo Query Code:

db.jobs.find({ "JobModel.Category" : "full time", 
"JobModel.Title" : /.*manager.*/i })  

Some Useful Regex:

  • this regex will search all the records which contains textToSearch and ignores case. textToSearch = "/.*" + textToSearch + ".*/i";
  • this regex will search all the records which starts with textToSearch and ignores case. textToSearch = "/^" + textToSearch + "/i";
  • this regex will search all the records which starts with textToSearch and do not ignores case. textToSearch = "/.*" + textToSearch + ".*/";

Solution 5

Thanks to @Sridhar - similar aproach that worked for me

public List<SearchModel> GetSearchResult(string searchParam) => _collection.Find(new BsonDocument { { "Datetime", new BsonDocument { { "$regex", searchParam }, { "$options", "i" } } } }).ToList(); // Search DateTime "Like"