Home > Mobile >  C# Searching MongoDB string that starts with "xyz"
C# Searching MongoDB string that starts with "xyz"

Time:08-08

I try to code a Storagesystem and i got one Problem and dont know how to solve it...

       public static List<string> GetAllItemsFromDB(string Searchbar)
        {
            List<string> retList = new List<string>();

            retList.Clear();

            var filter = Builders<DB_Package_Item>.Filter.Eq(Item => Item.Item_Name, Searchbar);

            var ItemsMatch = Item_DB.Find(filter).ToList();

           foreach (var Item in ItemsMatch.ToList())
            {
                retList.Add(Item.Item_Name);
            }

            return retList;
        }

This Works. But when i change the filter to:

var filter = Builders<DB_Package_Item>.Filter.ElemMatch(Item => Item.Item_Name, Searchbar);

It crasches as soon i type any char in the searchbar with Error code : "System.InvalidOperationException: "The serializer for field 'Item_Name' must implement IBsonArraySerializer and provide item serialization info." "

I just dont get it why...

This is the Data_Package for MongoDB

public class DB_Package_Item
    {
        public Guid Id { get; set; }
        public int Item_ID { get; set; }
        public int Box_ID { get; set; }
        public string Item_Name { get; set; }
        public int Quantity { get; set; }
        public string Partnumber { get; set; }
        public string Supplier { get; set; }
    }

Thx for every help!

CodePudding user response:

FilterDefinitionBuilder<TDocument>.ElemMatch<TItem> or $elemMatch operator is for searching the item in the array field, which is not appropriate for your scenario to search (term) for a string field.

You need the $regex operator which is FilterDefinitionBuilder<TDocument>.Regex in C# syntax.

using System.Text.RegularExpressions;

var filter = Builders<DB_Package_Item>.Filter.Regex(Item => Item.Item_Name
    , new Regex("^"   Searchbar));

For case-insensitive:

new Regex("^"   Searchbar, RegexOptions.IgnoreCase)

Or

var filter = Builders<DB_Package_Item>.Filter.Regex(Item => Item.Item_Name
    , new BsonRegularExpression("^"   Searchbar));

For case-insensitive,

new BsonRegularExpression("^"   Searchbar, "i")
  • Related