无法在MongoDB和C#驱动程序中重现sum聚合

时间:2015-03-01 23:03:38

标签: c# mongodb

这个MongoDB本机查询工作正常:

db.collection.aggregate([
    {$project:{hour:{$hour:'$CreatedAt'},day:{$dayOfMonth:'$CreatedAt'},month:{$month:'$CreatedAt'},year:{$year:'$CreatedAt'}}},
    {$group:{_id:{hour:'$hour',day:'$day',month:'$month',year:'$year'}, count: {$sum:1}}}
])

...但是当我尝试在C#中重现相同的查询时,每个总和的结果为0(在Robomongo中运行本机查询时不是这种情况)。

这是C#代码。我没有看到两者之间有任何差异......

public Dictionary<DateTime, Int32> GetSumPerHour()
{

    var project = new BsonDocument
    {
        {
            "$project", 
            new BsonDocument{
            {"hour", new BsonDocument{{"$hour","$CreatedAt"}}},
            {"day", new BsonDocument{{"$dayOfMonth","$CreatedAt"}}},
            {"month", new BsonDocument{{"$month","$CreatedAt"}}},
            {"year", new BsonDocument{{"$year","$CreatedAt"}}},
            }
        }
    };

    var group = new BsonDocument 
    { 
        { 
            "$group", 
            new BsonDocument 
                { 
                    {"_id", new BsonDocument {{"hour","$hour"},{"day","$day"},{"month","$month"},{"year","$year"}}}, 
                    {"count", new BsonDocument {{"$sum","1"}} }
                } 
        } 
    };

    var pipeline = new[] { project, group };
    var arguments = new AggregateArgs { Pipeline = pipeline };
    var results = this.collection.Aggregate(arguments);

    var timeValueDictionary = new Dictionary<DateTime, Int32>();

        foreach (BsonDocument result in results)
        {

            int hour = result["_id"]["hour"].AsInt32;
            int day = result["_id"]["day"].AsInt32;
            int month = result["_id"]["month"].AsInt32;
            int year = result["_id"]["year"].AsInt32;

            DateTime time = new DateTime(year, month, day, hour, 0, 0);
            int count = result["count"].AsInt32;

            timeValueDictionary.Add(time, count);

        }            

    return timeValueDictionary;

}

0 个答案:

没有答案