举例:查询出 同一IP一天内点击专线消耗竞价物流币的量
关键点:
1、怎么取出当天的数据?
2、怎样实现根据IP分组,并且计算出消耗的物流币总数量?
步骤:
1、返回当天零点的时间戳
DateTime now = DateTime.Now; DateTime now_0 = new DateTime(now.Year, now.Month, now.Day); long unixtemp = 0; string TheTimeStamp = TimeHelper.GetTimeStamp(now_0); if (!long.TryParse(TheTimeStamp, out unixtemp)) { return 0; }
2、创建查询管道
string pipelineJson1 = " { $match : {ip:'" + ip + "',state:1,unixTime:{$gte:" + unixtemp + "}} }"; string pipelineJson2 = @"{$group:{_id:'$ip',all_jingjiapx:{$sum:{$add:['$jingjia_PX','$basic_PX']}}}} ";
IList<IPipelineStageDefinition> stages = new List<IPipelineStageDefinition>(); PipelineStageDefinition<BsonDocument, BsonDocument> stage1 =new JsonPipelineStageDefinition<BsonDocument, BsonDocument>(pipelineJson1); PipelineStageDefinition<BsonDocument, BsonDocument> stage2 =new JsonPipelineStageDefinition<BsonDocument, BsonDocument>(pipelineJson2); stages.Add(stage1); stages.Add(stage2); var pipeline = new PipelineStagePipelineDefinition<BsonDocument, BsonDocument>(stages);
3、执行查询
var a = MongoDbHelper.GetDb().GetCollection<BsonDocument>("PageColllection").Aggregate(pipeline).ToList();
4、从返回的结果中查询出消耗的物流币总量
a[0].GetElement("all_jingjiapx").Value.ToString().Length > 0 ? Convert.ToInt32(a[0].GetElement("all_jingjiapx").Value.ToString()) : 0;
整个方法如下所示
/// <summary> /// 规则 : /// 同一IP一天内点击专线消耗竞价物流币的量 /// </summary> /// <param name="ip"></param> /// <returns></returns> public int AntiEvilclickRuleSeven(string ip) { DateTime now = DateTime.Now; DateTime now_0 = new DateTime(now.Year, now.Month, now.Day); long unixtemp = 0; string TheTimeStamp = TimeHelper.GetTimeStamp(now_0); if (!long.TryParse(TheTimeStamp, out unixtemp)) { return 0; } string pipelineJson1 = " { $match : {ip:'" + ip + "',state:1,unixTime:{$gte:" + unixtemp + "}} }"; string pipelineJson2 = @"{$group:{_id:'$ip',all_jingjiapx:{$sum:{$add:['$jingjia_PX','$basic_PX']}}}} "; IList<IPipelineStageDefinition> stages = new List<IPipelineStageDefinition>(); PipelineStageDefinition<BsonDocument, BsonDocument> stage1 = new JsonPipelineStageDefinition<BsonDocument, BsonDocument>(pipelineJson1); PipelineStageDefinition<BsonDocument, BsonDocument> stage2 = new JsonPipelineStageDefinition<BsonDocument, BsonDocument>(pipelineJson2); stages.Add(stage1); stages.Add(stage2); var pipeline = new PipelineStagePipelineDefinition<BsonDocument, BsonDocument>(stages); var a = MongoDbHelper.GetDb().GetCollection<BsonDocument>("PageColllection").Aggregate(pipeline).ToList(); if (a.Count <= 0) { return 0; } else { return a[0].GetElement("all_jingjiapx").Value.ToString().Length > 0 ? Convert.ToInt32(a[0].GetElement("all_jingjiapx").Value.ToString()) : 0; } }