2017-01-30 57 views
1

套裝在KeyValuePair獲得價值如下:MongoDB中該行結構如何從IMongoCollection

{ 
"_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 
    } 
    ] 
} 

我想通過PublishedDateSocialData,組得到的值。我在這一刻的代碼如下所示:

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()不支持,所以我應該如何獲取這些數據?

+0

[This](http://stackoverflow.com/questions/31171451/getting-a-single-object-from- mongodb-in-c-sharp)問題可能會有所幫助。 – RandomStranger

+0

我不認爲這是可能的,這是一個類似的問題已經:http://stackoverflow.com/questions/41902613/what-is-the-c-sharp-equivalent-of-push-and-root-for -mongodb/41903581#41903581我會得到整個字典和客戶端過濾器。或者是SocialMedia真的很大的字典? –

+0

@MaksimSimkin依賴於「ServiceType」SocialData最多可以有5個元素,所以它不是很大,而且鍵是唯一的。 –

回答

1

我不認爲,MongoDrive可以將其翻譯爲查詢。如果社交媒體不是非常高,我會得到整個字典,並在客戶端過濾它:

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 
      }); 
+0

非常感謝,正如我所說'在我看來SocialData'是小字典,所以這個解決方案應該適合我。 –

+0

@TomaszKowalczyk不客氣,如果它幫助你,我會感謝一個upvote :) –