Mongodb c#driver Linq查询分组

时间:2014-08-08 13:11:08

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

我的mongodb文档结构如下:(每个文档为每个术语创建每天)

{
    "_id" : ObjectId("53da1f0f12f0631d940f97a1"),
    "TermId" : "6cb28ca7-cc64-4b01-8dc5-b5f8d9fac9b5",
    "Term" : "priceless",
    "TotalCount" : 14,
    "date" : ISODate("2014-02-12T00:00:00.000Z"),
    "socialCounts" : [ 
        {
            "Name" : "twitter",
            "Count" : 3
        }, 
        {
            "Name" : "facebook",
            "Count" : 8
        },
        {
            "Name" : "Instagram",
            "Count" : 3
    ]
}

我需要

  • 我传入的每个termId的总数(每个TermID和总和(Totalcount))。
  • 我传入的所有期限ID的每个社交类型计数的总和。

我目前的方法只返回文件

public IQueryable<ReportingStats> GetReportingWallStats(List<string> terms, string[] sources, DateTime fr, DateTime to)
        {
            //var socialTypes = sources.ToBsonDocumentArray();
            try
            {
                var entities = from e in this.collection.AsQueryable<Collections.ReportingStats>()
                               where e.date >= fr && e.date <= to && terms.Contains(e.TermId) && e.TotalCount > 0
                               select e;
                var mongoQuery = ((MongoQueryable<ReportingStats>)entities).GetMongoQuery();
                var explain = entities.Explain();
                return entities;
            }
            catch (Exception ex)
            {
                Log.Error("Exception in  method GetReportingWallStats", ex);
                return null;
            }
        }

有人可以帮助我以下面的方式获得结果

dictionaryItem(“Term1”140)

dictionaryItem(“Term2”190)

dictionaryItem(“Term3”100)

dictionaryItem(“Term4”133)

进入字典和

dictionaryItem(“Facebook”1440)

dictionaryItem(“Twitter”1640)

dictionaryItem(“Instagram”1940)

以有效的方式进入另一个字典。

1 个答案:

答案 0 :(得分:1)

您可以编写map reduce查询,但这必须在Javascript而不是C#中完成,因为.Net驱动程序尚未支持groupby操作。来自http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/的.net / C#教程的示例:

var map =
"function() {" +
"    for (var key in this) {" +
"        emit(key, { count : 1 });" +
"    }" +
"}";

var reduce =
"function(key, emits) {" +
"    total = 0;" +
"    for (var i in emits) {" +
"        total += emits[i].count;" +
"    }" +
"    return { count : total };" +
"}";

var mr = collection.MapReduce(map, reduce);
foreach (var document in mr.GetResults()) {
    Console.WriteLine(document.ToJson());
}

Another example at Ode to Code