Mongodb c#驱动Linq查询组by
本文关键字:by 查询 Linq 驱动 Mongodb | 更新日期: 2023-09-27 18:17:02
我的mongodb文档结构如下:(每个文档创建每个Term Everyday)
{
"_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的Totalcount的总和(grouby each termId and sum(Totalcount))。
- 传入的所有Term id的每个Social type计数之和。
我的方法目前只返回文档
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(140年"Term1")
dictionaryItem(190年"Term2")
dictionaryItem(100年"Term3")
dictionaryItem(133年"Term4")
放入字典和
dictionaryItem(1440年"Facebook")
dictionaryItem(1640年"推特")
dictionaryItem(1940年"Instagram")
你可以写一个map reduce查询,但这必须用Javascript而不是c#来完成,因为。net驱动程序还不支持分组操作。一个来自。net/c#教程的例子:http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/:
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());
}
另一个例子在Ode to Code