如何从IMongoCollection中嵌套KeyValuePair获取值

时间:2017-01-30 13:00:59

标签: c# .net mongodb linq mongodb-.net-driver

MongoDB中的行结构如下:

{
"_id" : ObjectId("588b0fe98dc6911c54a43be6"),
"GrId" : 1,
"GrTitle" : "GrTitle",
"ServiceType" : 1,
"Url" : "https://twitter.com/xxxxxxxxxx",
"PublishedDate" : ISODate("2017-01-27T09:15:08.000Z"),
"ScrappedDate" : ISODate("2017-01-27T09:16:25.097Z"),
"Keyword" : "keyword",
"ItemId" : "123123",
"SearchType" : 2,
"Content" : "content",
"SocialData" : [ 
    {
        "k" : "Retweets",
        "v" : 0
    }, 
    {
        "k" : "Favorites",
        "v" : 1
    }
  ]
}

我想从SocialData获取PublishedDate的值,var filter = collection.Aggregate() .Match(r => r.PublishedDate <= to) .Match(r => r.PublishedDate >= from); if (serviceType.HasValue) filter = filter.Match(r => r.ServiceType == serviceType); if (gameId.HasValue) filter = filter.Match(r => r.GrId == gameId.Value); return filter .Group( r => new { groupedYear = r.PublishedDate.Year, groupedMonth = r.PublishedDate.Month, groupedDay = r.PublishedDate.Day, itemId = r.ItemId, }, g => new { Key = g.Key, RetweetsValue = g.FirstOrDefault().SocialData.Select(s => new KeyValuePair<string, int>(s.Key, s.Value)).FirstOrDefault(k => k.Key == "Retweets").Value }) .Project( r => new ChartSummary { SocialMedia = r.RetweetsValue, Day = r.Key.groupedDay, Month = r.Key.groupedMonth, Year = r.Key.groupedYear, }) .ToList(); 。我这时的代码看起来像这样:

FirstOrDefault()

我收到异常,{{1}}不受支持,那么我应该如何检索这些数据呢?

1 个答案:

答案 0 :(得分:1)

我不认为,MongoDrive可以将其翻译为查询。如果SocialMedia不是很高兴我会得到整本字典并在客户端过滤它:

    return filter
            .Group(
                r => new
                {
                    groupedYear = r.PublishedDate.Year,
                    groupedMonth = r.PublishedDate.Month,
                    groupedDay = r.PublishedDate.Day,
                    itemId = r.ItemId,
                },
                g => new
                {
                    Key = g.Key,
                    RetweetsValue = g.First().SocialData
                })
            .Project(
                r => new 
                {
                    SocialMedia = r.RetweetsValue,
                    Day = r.Key.groupedDay,
                    Month = r.Key.groupedMonth,
                    Year = r.Key.groupedYear,
                })
            .ToList()               
            .Select(
            r => new ChartSummary
            {
                SocialMedia = r.SocialMedia.FirstOrDefault(x=>x.Key=="Retweets").Value,
                Day = r.Day,
                Month = r.Month,
                Year = r.Year
            });