dhrm
dhrm

Reputation: 14944

Mongo C# filter on integer contains

I've a collection with orders, each with an OrderId field of type int32. I would like to filter the collecting and get all orders where the OrderId contains e.g. 123. For instance the following OrderIds must match:

The following raw mongo filter works: { $where: "/^.*123.*/.test(this.OrderId)" }

How can this be expressed in the C# Mongo client or something different that does the job?

I'm not able to use the below code, as it seems to only work in string fields:

Builders<Order>.Filter.Regex(x => x.OrderId, new BsonRegularExpression("123"))

Upvotes: 4

Views: 1447

Answers (4)

David Oganov
David Oganov

Reputation: 1374

You can use Filter.Regex to achieve the desired behavior:

var valueToFilterBy = "123"
var filter = Builders<Order>.Filter.Regex(nameof(Order.Id), new BsonRegularExpression($".*{valueToFilterBy}.*"));
var data = await collection.FindAsync(filter).ToListAsync();

Upvotes: -1

K-attila-
K-attila-

Reputation: 101

Did you try using:

x => x.OrderId.ToString() 

instead of

x => x.Orderid

Upvotes: 0

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5679

ideally you should store a string version of the order id in your documents. in case that's not an option you can do the following aggregation pipeline:

var res = await collection
    .Aggregate()
    .AppendStage<object>("{ $set : { orderIdString : { $toString : '$OrderId' } } }")
    .Match(Builders<object>.Filter.Regex("orderIdString", "/123/"))
    .AppendStage<object>("{ $unset : 'orderIdString' }")
    .As<Order>()
    .ToListAsync();

Upvotes: 2

dododo
dododo

Reputation: 4897

I don't think you can generate $where via typed builders. So, as it was mentioned above, the only option you have is to create a filter from a raw MQL like below:

    var coll = db.GetCollection<Order>("coll");
    var result = coll.Find("{ $where: '/^.*123.*/.test(this.OrderId)' }").ToList();

Upvotes: 0

Related Questions