mongo java driver3.4,MongoDB Java Driver 3.4操作

谢善
2023-12-01

查询文档

用来打印查询结果 BlockprintBlock = new Block() {

@Override

public void apply(Document document) {

System.out.println(document.toJson());

}

};

查询所有文档 collection.find().forEach(printBlock);

collection.find(new Document()).forEach(printBlock);

复合查询 collection.find(eq("name", "sue")).forEach(printBlock); // 通过过滤器查询

collection.find(and(gte("age", 20), lt("age", 30), eq("type", 2))).forEach(printBlock); // 通过Filters 过滤

collection.find(new Document("age", new Document("$gte", 20).append("$lt", 30)).append("type", 2)).forEach(printBlock); // 通过 filter document 过滤

返回指定的查询字段 collection.find().projection(new Document("name", 1).append("age", 1).append("type", 1).append("_id", 0)).forEach(printBlock); // 通过.projection()指定返回的字段

collection.find().projection(fields(include("name", "age", "type"), excludeId())).forEach(printBlock); // 通过Projections类过滤

排序 collection.find().sort(Sorts.ascending("name")).forEach(printBlock); // 通过.sort() Sorts类排序

 类似资料: