11月4日

今天做数据库测试,我事先以为是做连接mongo的增删改查,但是做的mongo的复杂查询,我之前做的是简单查询,然后想在基础上进行实现。然后发现,这部分内容很少尤其是聚合查询,大多数都是在命令行中进行操作,java操作的代码特别少而且几乎看不懂。后来学习同学的实现代码如下

 public void cha() {
MongoCollection<Document> collection = database.getCollection("data");
//这个doc 是为了分组
Document doc = new Document();
doc.append("_id", "$id");
// doc.append("type", "$type");
doc.append("count", new Document("$sum", 1));

Document matchDoc = new Document();
// r1_video
// matchDoc.put("type", "video");
// r1_article
// matchDoc.put("type", "article");
Document group = new Document("$group", doc);
// Document match = new Document("$match", matchDoc);

Document sort = new Document("$sort", new Document("count", -1));
Document limit = new Document("$limit", 10);
List<Document> doclist = new ArrayList<Document>();
doclist.add(group);
// doclist.add(match);
doclist.add(sort);
doclist.add(limit);

AggregateIterable<Document> aggregate = collection.aggregate(doclist);
MongoCursor<Document> iterator = aggregate.iterator();
while (iterator.hasNext()) {
Document next = iterator.next();
String encode = next.getString("_id");
String s = next.getString("traffic");

int count = next.getInteger("count", 0);
System.out.println(encode + " " + count+ " " + s);
}


}

但是我发现两个问题,他的group后面只能跟一个参数,group by xx,xx  不知道怎么实现,还有就是这样实现好像只写了select语句的from 后面部分,对于select xx,xx,这里想要参数的设置我也不知道怎么实现。

学习时间:19:01 到23:42

原文地址:https://www.cnblogs.com/buyaoya-pingdao/p/15511733.html