0

we have a grid and there have multiple columns in the grid like product name,product details ,product id etc. all other fields working fine with partial contains search

But have issue with objectid in partial serach throws a below error. Index was outside the bounds of the array .

Here is the code block

   var builder = Builders<T>.Filter;

            var filterQuery = builder.Where(s => s.Id != null);

         if (!string.IsNullOrWhiteSpace(ProductName))
            {
                filterQuery &= builder.Where(s => s.ProductName.ToLower().Contains(ProductName.ToLower()));
            }

     // Working fine with contains partial search


            if (!string.IsNullOrWhiteSpace(ProductId))
            {

soln 1: Not working
                 BsonObjectId id = new BsonObjectId(new ObjectId(ProductId));

                  filterQuery &= builder.Where(s => s.Id.Equals(id));
               

     //    solution 2

            filterQuery &= builder.Eq("_id", ObjectId.Parse(ProductId)); // now tried this not working

               }


soln 3: not working

   //filterQuery &= builder.Where(s=>s.Id==ObjectId.Parse(ProductId)).ToString();


finally we are passing the filter query variable into find for multiple filter 

          var recordCount = await Collection.Find(filterQuery).CountDocumentsAsync();
            var endQuery = Collection.Find(filterQuery).SortBy(x => x.InitiationTimestamp).Skip((page - 1) * pagesize).Limit(pagesize);
            return (await endQuery.ToListAsync(), recordCount);

tried below one not working. https://stackoverflow.com/questions/14315684/query-mongodb-using-objectid#:~:text=In%20C%23%20for%20latest%20official%20MongoDB.Driver%20write%20this-,result%20without%20converting%20id%20from%20string%20to%20ObjectId.

Note : equal is working, problem with partial search

input:

**Actual Object id: "50ed4e7d5baffd13a44d0153"

Tried input id: "50ed4e7d"

O.p: error index was outside the bounds of the array**

Mohamed Sahir
  • 2,482
  • 8
  • 40
  • 71
  • related: https://stackoverflow.com/questions/17836989/mongo-objectid-contains-query – Christoph Lütjen Dec 17 '22 at 15:59
  • @ChristophLütjen But that answer looks like if user enter 50ed - remaining letters we need to add as 0 to l meet length 32 and then do the search any other way with c# – Mohamed Sahir Dec 17 '22 at 16:12
  • 4
    I've not tested this, but the key is, that ObjectIds simply are no text and so you cannot "add letters". The answer says, that you have to create two ObjectIds that you can see as NUMBERS and then you do a numeric search greater than the first number and lower than the second one. Obviously that works for "starts with" queries only. "contains" is simply not possible with ObjectIds. – Christoph Lütjen Dec 17 '22 at 16:20

0 Answers0