1

I have a BsonDocument like

{

"Code" : "123ACThe three $#^",

. . . . 

}

I want to find the records which is having 3AC anywhere in the string in the field Code

note :- the characers AC should be case insensitive

I am new to mongoDb.How to achieve this ? Thanks in Advance for replies.

UPDATE

I tried this code db.session.find({ "Code": { "$regex": '^(.?(\b3AC\b)[^$])$' } } );

Got this working

db.session.find({ "Code": { "$regex": '3AC.*'} } );

Is this the only way ? and how to achieve in C# using native driver ?

1
  • Added an answer that shows how to do this in C#. Commented Nov 7, 2013 at 19:15

3 Answers 3

1

This should do the trick:

db.session.find({Code: /3AC/ })

or if you want to ignore case:

db.session.find({Code: /3AC/i }) 
Sign up to request clarification or add additional context in comments.

Comments

1

While doing a search like that is not generally recommended as an index cannot be used (as your expression is not anchored to the start of the string), in C# you can use the Query classes' Matches method:

Query.Matches("Code", "3AC.*")

where "3AC.*" represents the regular expression string you're using.

MongoCollection<ExampleType> exampleCollection;
var query = Query.Matches("Code", "3AC.*");
foreach (var example in exampleCollection.Find(query)) {
    //
}

Comments

1

You can also use the driver's LINQ interface and the driver will build the regular expression for you:

var query = sessionCollection.AsQueryable<Session>()
    .Where(s => s.Code.Contains("3AC"));
foreach (var session in query) { ... }

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.