@[TOC]记录学习MongoDB数据库的点滴
前言
苦练七十二变,才敢笑对八十一难,演戏如此,人生也亦然。与君共勉。
初入社会
毕业后, 承蒙公司赏识,我得以找到自己人生中的第一份工作,开始闯编码之路。在工作中接触到大学时只闻其名的NoSQL数据库时,整个人头都大了,通过在网上查询和自己实验,得出下面这一堆使用方法,遂记录下来,以备不时之需。
正文
MongoDB数据库
假设当前有个MongoDB集合t_group_user,集合中一条数据如下图
分析这个集合中的数据,与之对应就是一个对象A中包含属性{duration,attributes,dateTime,event,timeStamp},其中attributes又是一个对象包含属性{response,ErrorCode,params,url};dateTime对象包含属性{timeStamp,date,year,month,week,hour,timeStr,day}
- 查询字段值匹配
// An highlighted block
db.getCollection("t_group_user").find(
{ $and : [{"attributes.ErrorCode" : 0},
{"dateTime.timeStamp" : "1241241241241"}] });
转化为java语言
// An highlighted block
Query query = new Query();
query.addCriteria(Criteria.where("attributes.ErrorCode").is(0)
.and("dateTime.timeStamp").is(1241241241241));
mongoTemplate.find(query,attributes.class,"t_group_user");
- 排序
// An highlighted block
db.getCollection("t_group_user").find().sort({字段:1,...});
参数1为升序排列
参数-1为降序排列
多个字段时就近原则
转为java语言
// An highlighted block
Query query = new Query();
//按timeStamp倒序排列
Sort sort= Sort.by(Sort.Direction.DESC,"timeStamp");
query.with(sort);
mongoTemplate.find(query,attributes.class,"t_group_user");
- 求和
// An highlighted block
db.getCollection("t_group_user").find().count();
转为java语言
// An highlighted block
mongoTemplate.count(query, attributes.class, "t_group_user");
- 聚合查询
下面这段代码是copy,直接数据库查询就是类似代码
// An highlighted block
db.getCollection("user_list").aggregate(
//查询条件
{ $match: { name: '小李' } },
//字段重新处理,增加额外需要的字段并赋值
{ $project: {
"year": {"$substr": ["$create_time", 0, 4] },
"month": { "$substr": ["$create_time", 5, 2] },
"day":{"$substr": ["$create_time", 8, 2] }
} },
{ $group: {
_id:{year:"$year",month:"$month",day:"$day"},
total: { $sum: 1 }
} }
)
聚合查询在java中的书写
// An highlighted block
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("comId").is(comId)
.and("type").is("appCountByDay")
.and("year").is(timeDate.getYear())
.and("month").is(timeDate.getMonth())),
//以agId分组,.first("字段")会显示出来
Aggregation.group("agId")
.first("agentId").as("agentId")
.sum("count").as("count")
.first("name").as("name")
.first("year").as("year")
.first("month").as("month"),
//添加排序
Aggregation.sort(Sort.Direction.DESC, "count"),
//添加查询返回限制个数
Aggregation.limit(number)
);
AggregationResults<APPLog> apiLogs
= mongoTemplate.aggregate(agg, "t_group_user", APPLog.class);
List<APPLog> logs = apiLogs.getMappedResults();
- 字段存在且值不为空
// An highlighted block
query.addCriteria(Criteria.where("agId").ne("null").exists(true));
结语
书山有路勤为径,学海无涯苦作舟。作为一只菜菜的程序猿,干就对了!
(ps:如果后续有新体会,会继续记录)