Mongo C# filter on integer contains

Viewed 671

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:

  • 123
  • 9912399
  • 99123

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"))
4 Answers

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();

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();

Did you try using:

x => x.OrderId.ToString() 

instead of

x => x.Orderid

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();
Related