0

I want to fetch data from mongo using comma separated string in C#. Below is my code.

 string numbers = "32,12,56,78";
 List<CustomerNumbers> calling_number= new List<CDRs>();

 IMongoCollection<CustomerNumbers> Collec;

 calling_number= Collec.Find(x => x.customer == ID && x.numbers.Contains(numbers)).ToList();

I am new to mongo and and did't know the exact approach. while using above code I am getting records for single number. Please guide me to fix this. TIA

Class structure

public class CustomerNumbers
{
    public string numbers { get; set; }
    public int customer { get; set; }
}

1 Answers1

0

Ideally, you'd have modeled your numbers field in mongo as an array rather than a delimited string, this would allow you to add indexes and performance tune your queries.

However, we can make use of the aggregation pipeline for this. We'll need an extra class like the following that we'll use:

    public class CustomerNumbersSplit
    {
        public string[] numbers { get; set; }
        public int customer { get; set; }
    }

We'll also need to do is split your comma-delimited string.

var numbers = "32,12,56,78";

var numbersSplit = numbers.Split(",", StringSplitOptions.RemoveEmptyEntries)
    .Select(int.Parse)
    .ToArray();

Once we've done that we can then write a query as the following:

var result = await collection.Aggregate()
    .Match(x => x.customer == ID)
    .AppendStage<CustomerNumbersSplit>(@"{ $addFields: { numbers: { $split: [""$numbers"", "","" ] } } }")
    .Match(x => x.numbers.Any(y => numbersSplit.Contains(y)))
    .ToListAsync();

This makes use of a $split and $addFields, this is so we can use the database engine to split the number and query them in the database engine.

If you're interested in the query that it generated:

[
  { "$match" : { "customer" : 12324 } },
  { "$addFields" : { "numbers" : { "$split" : ["$numbers", ","] } } },
  { "$match" : { "numbers" : { "$elemMatch" : { "$in" : ["32", "12", "56", "78"] } } } }
]
Kevin Smith
  • 13,746
  • 4
  • 52
  • 77
  • I have added the class structure numbers are of sting datatype and customer is of int. can you please modify your code accordingly . Thanks – pankash mann Mar 05 '20 at 11:15
  • Updated, I'd advise re-modeling your database for your query usage. It would be better practice to have your numbers as an array. – Kevin Smith Mar 05 '20 at 11:35