Cyrus the Great
Cyrus the Great

Reputation: 5932

Use regex filter at mussy string in mongodb

I have these kind of strings that I get from my mongo collection:

"{\"Id\":\"4573358d-8cac-44a4-85e0-2343wres4321\",\"CreationDateTime\":\"\\/Date(1477834196111)\\/\",\"DeviceId\":\"\",\"UserId\":\"b9cdd9d3-4ac8-4f95-8s44-1234wre44321\",\"UserFullName\":\"groot\",\"SystemId\":\"monitoring\",\"SystemTitle\":\"monitoring\",\"EventId\":\"monitoring.events.udutyallcalculates\",\"EventTitle\":\"xxxx\",\"EventData\":[{\"Key\":\"LogID\",\"Value\":\"\",\"Children\":null},{\"Key\":\"SessionId\",\"Value\":\"GUID\",\"Children\":null},{\"Key\":\"Version\",\"Value\":\"Host- Version=1111\",\"Children\":null}],\"BusinessCode\":\"2-10-102606-46-1-0-0\",\"ProcessId\":\"00000000-0000-0000-0000-000000000000\",\"WorkItemId\":ttt,\"WKT\":\"\"}"

before query I have to declare a filter because I want that kind of information that BusinessCode started with 1-. Now I am writing this filter :

filters.Add(Builders<Message>.Filter.Where(x => x.Payload.Contains("BusinessCode\":\"" + area + "-")));

this filter return BusinessCode that start with 1.

12 and other integer that started with 1 are contains.I want to use regex but how could I use this command? I have written this :

filters.Add(Builders<Message>.Filter.Regex(x => x.Payload.Contains("BusinessCode\":\"" + area + "-"), "/^" + area + "/-"));

but when I do query from my collection :

"var messages = GetDbMongo().GetCollection<Message>(DB_COLLECTION_MESSAGES)
                .Find(Builders<Message>.Filter.Or(filters)).Sort(sort).Limit(count <= 0 ? 10 : count).ToList();"

I got this error:

Unable to determine the serialization information for x => Convert(x.Payload.Contains((("BusinessCode":"" + Convert(value(Notifications.Common.DAL+<>c__DisplayClass30_0).area)) + "-"))).

area = 1

Upvotes: 0

Views: 135

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14436

You're using the Builders<Message>.Filter.Regex incorrectly, you only need to pass the expression to the property and the regex you want to use:

var codeRegex = @"1[^\""]*";
var regex = $@"\\""BusinessCode\\"":\\\""{codeRegex}\\""";

Builders<Message>.Filter.Regex(x => x.Payload, regex)

Upvotes: 1

Related Questions