Search code examples
c#mongodbmongodb-.net-driver

How can I access List<KeyValuePair<string,int>> from MongoDB


I am storing in MongoDB records with the following definition:

public class StorageRecord
{
    public int GrId { get; set; }
    public List<KeyValuePair<string,int>> Data { get; set; }
}

and sample like this one below:

var storageRecord = new StorageRecord
{
GrId = 12,
Data = new List<KeyValuePair<string, int>>()
    {
        new KeyValuePair<string, int>("xx", 12),
        new KeyValuePair<string, int>("yy", 13),
        new KeyValuePair<string, int>("zz", 14)
    }
}

Please tell me how should I write the query to retrive the Sum of all of the records which has for example xx key in the Data list of KeyValuePair.

I have started with the following statement but don't know what should be next:

var TotalXX = collection
            .Where(r => r.GrId == grId)
            .GroupBy(t => t.GrId)
            .Select(v => v.Select(c => c.Data));

Solution

  • I think you don't need the GroupBy:

    var TotalXX = collection
       .Where(storage => storage.GrId == grId)
       .Sum(storage => storage.Data.Count(kv => kv.Key == "xx"));