我想按天分组聚合(不是dayOfMonth或Year,只是绝对日)。因此,我想使用here $dateToString
$dateToString: { format: "%Y-%m-%d", date: "$date" }
所示的var groups = await collection.Aggregate()
.Match(job => /*...*/)
.Group(job => job.Created.ToString(),
group => /*...*/)
.ToListAsync();
运算符。有没有办法为此使用表达式:
-s
我收到此错误:
表达式树{document} {created} .ToString ...
不支持System.DateTime类型的ToString
答案 0 :(得分:0)
在@Blakes Seven评论的帮助下,我用另一个分组键解决了原始问题。
var groups = await collection.Aggregate()
.Match(job => /*...*/)
.Group(job => new
{
Year = job.Created.Year,
Month = job.Created.Month,
Day = job.Created.Day
},
group => new { Key = group.Key, Value = group.Count() })
.ToListAsync();
修改强>
为了支持 day 以外的其他时段,我必须使用BsonDocument
。
var groupBy = new BsonDocument
{
{
"_id", new BsonDocument
{
{ "$add", new BsonArray
{
new BsonDocument
{
{ "$subtract", new BsonArray
{
new BsonDocument { { "$subtract", new BsonArray
{
"$created",
new DateTime(0) }
}
new BsonDocument { { "$mod", new BsonArray
{
new BsonDocument
{
{ "$subtract", new BsonArray
{
"$created",
new DateTime(0)
}
}
},
msPerPeriod
}
} }
}
}
},
new DateTime(0)
}
}
}
},
{ "count", new BsonDocument("$sum", 1) } };
var groups = await collection.Aggregate()
.Match(job => job.Created >= since && regex.IsMatch(job.Definition))
.Group(groupBy)
.Sort(Builders<BsonDocument>.Sort.Ascending(doc => doc["_id"]))
.ToListAsync();