MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别。例如用Document替换BasicDBObject、通过Builders类构建Bson替代直接输入$命令等,本文整理了基于3.2版本的常用增删改查操作的使用方法。为了避免冗长的篇幅,分为增删改、查询、聚合、地理索引等几部分。
先看用于演示的类的基本代码
- import static com.mongodb.client.model.Filters.*;
- import static com.mongodb.client.model.Projections.*;
- import static com.mongodb.client.model.Sorts.*;
-
- import java.text.ParseException;
- import java.util.Arrays;
-
- import org.bson.BsonType;
- import org.bson.Document;
-
- import com.mongodb.Block;
- import com.mongodb.MongoClient;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- import com.mongodb.client.model.Projections;
-
- public class FindExamples {
-
- public static void main(String[] args) throws ParseException {
-
- MongoClient mongoClient = new MongoClient("localhost", 27017);
- MongoDatabase database = mongoClient.getDatabase("lesson");
-
- FindExamples client = new FindExamples(database);
- client.show();
- mongoClient.close();
- }
-
- private MongoDatabase database;
- public FindExamples(MongoDatabase database) {
- this.database = database;
- }
-
- public void show() {
- MongoCollection<Document> mc = database.getCollection("blog");
-
- mc.drop();
-
-
- Document doc1 = new Document("title", "good day").append("owner", "tom").append("words", 300)
- .append("comments", Arrays.asList(new Document("author", "joe").append("score", 3).append("comment", "good"), new Document("author", "white").append("score", 1).append("comment", "oh no")));
- Document doc2 = new Document("title", "good").append("owner", "john").append("words", 400)
- .append("comments", Arrays.asList(new Document("author", "william").append("score", 4).append("comment", "good"), new Document("author", "white").append("score", 6).append("comment", "very good")));
- Document doc3 = new Document("title", "good night").append("owner", "mike").append("words", 200)
- .append("tag", Arrays.asList(1, 2, 3, 4));
- Document doc4 = new Document("title", "happiness").append("owner", "tom").append("words", 1480)
- .append("tag", Arrays.asList(2, 3, 4));
- Document doc5 = new Document("title", "a good thing").append("owner", "tom").append("words", 180)
- .append("tag", Arrays.asList(1, 2, 3, 4, 5));
- mc.insertMany(Arrays.asList(doc1, doc2, doc3, doc4, doc5));
-
-
- FindIterable<Document> iterable = mc.find();
- printResult("find all", iterable);
-
-
- }
-
-
- public void printResult(String doing, FindIterable<Document> iterable) {
- System.out.println(doing);
- iterable.forEach(new Block<Document>() {
- public void apply(final Document document) {
- System.out.println(document);
- }
- });
- System.out.println("------------------------------------------------------");
- System.out.println();
- }
- }
如上面代码所示,把所有的查询操作集中在show()方法中演示,并且在执行后打印结果集以观察查询结果。下面来填充show()方法
-
- mc.createIndex(new Document("words", 1));
-
- mc.createIndex(new Document("title", 1).append("owner", -1));
-
- mc.createIndex(new Document("title", "text"));
-
-
- FindIterable<Document> iterable = mc.find();
- printResult("find all", iterable);
-
-
- iterable = mc.find(new Document("title", "good"));
- printResult("find title=good", iterable);
-
-
- iterable = mc.find(new Document("title", "good").append("owner", "tom"));
- printResult("find title=good and owner=tom", iterable);
-
-
- iterable = mc.find(and(regex("title", "good"), eq("owner", "tom")));
- printResult("find title like %good% and owner=tom", iterable);
-
-
- iterable = mc.find().sort(ascending("title"));
- printResult("find all and ascending title", iterable);
-
-
- iterable = mc.find().sort(ascending("owner", "title"));
- printResult("find all and ascending owner,title", iterable);
-
-
- iterable = mc.find().sort(descending("words"));
- printResult("find all and descending words", iterable);
-
-
- iterable = mc.find(new Document("$or", Arrays.asList(new Document("owner", "tom"), new Document("words", new Document("$gt", 350)))));
- printResult("find owner=tom or words>350", iterable);
-
-
- iterable = mc.find().projection(include("title", "owner"));
- printResult("find all include (title,owner)", iterable);
-
-
- iterable = mc.find().projection(exclude("title"));
- printResult("find all exclude title", iterable);
-
-
- iterable = mc.find().projection(excludeId());
- printResult("find all excludeId", iterable);
-
-
- iterable = mc.find().projection(fields(include("title", "owner"), excludeId()));
- printResult("find all include (title,owner) and excludeId", iterable);
-
-
- iterable = mc.find(new Document("comments.author", "joe"));
- printResult("find comments.author=joe", iterable);
-
-
- iterable = mc.find(new Document("comments.author", "white").append("comments.score", new Document("$gt", 2)));
- printResult("find comments.author=white and comments.score>2 (wrong)", iterable);
-
-
- iterable = mc.find(Projections.elemMatch("comments", Filters.and(Filters.eq("author", "white"), Filters.gt("score", 2))));
- printResult("find comments.author=white and comments.score>2 using elemMatch", iterable);
-
-
- iterable = mc.find(Filters.regex("title", "^good")).projection(slice("comments", 1));
- printResult("find regex ^good and slice comments 1", iterable);
-
-
- iterable = mc.find(text("good"));
- printResult("text good", iterable);
-
-
- iterable = mc.find(eq("title", "good"));
- printResult("Filters: title eq good", iterable);
-
-
- iterable = mc.find(in("owner", "joe", "john", "william"));
- printResult("Filters: owner in joe,john,william", iterable);
-
-
- iterable = mc.find(nin("owner", "joe", "john", "tom"));
- printResult("Filters: owner nin joe,john,tom", iterable);
-
-
- iterable = mc.find(in("comments.author", "joe", "tom"));
- printResult("Filters: comments.author in joe,tom", iterable);
-
-
- iterable = mc.find(ne("words", 300));
- printResult("Filters: words ne 300", iterable);
-
-
- iterable = mc.find(and(eq("owner", "tom"), gt("words", 300)));
- printResult("Filters: owner eq tom and words gt 300", iterable);
-
-
- iterable = mc.find(and(or(eq("words", 300), eq("words", 400)), or(eq("owner", "joe"), size("comments", 2))));
- printResult("Filters: (words=300 or words=400) and (owner=joe or size(comments)=2)", iterable);
-
-
- iterable = mc.find(eq("tag.1", 2));
- printResult("Filters: tag.1 eq 2", iterable);
-
-
- iterable = mc.find(all("tag", Arrays.asList(1, 2, 3, 4)));
- printResult("Filters: tag match all (1, 2, 3, 4)", iterable);
-
-
- iterable = mc.find(exists("tag"));
- printResult("Filters: exists tag", iterable);
-
- iterable = mc.find(type("words", BsonType.INT32));
- printResult("Filters: type words is int32", iterable);
这里列出的查询方式可以覆盖到大部分开发需求,更多查询需求请参考官方文档。
(完)
个人补充--参考代码:
// 先从collection中取出最后的日期
if (queryFields.indexOf("datetime") > -1) {
FindIterable<Document> iter = null;
String datetime = getParam("datetime").toString();
if ("last".equals(datetime)) {
iter = collection.find().projection(Projections.include("datetime")).sort(Sorts.descending("datetime")).limit(1);
} else {
iter = collection.find(Filters.lte("datetime", Integer.parseInt(datetime))).projection(Projections.include("datetime")).sort(Sorts.descending("datetime")).limit(1);
}
iter.forEach(new Block<Document>() {
public void apply(Document doc) {
setParams("datetime", doc.getInteger("datetime"));
}
});
}
// 生成查询条件
Bson[] filters = new Bson[queryFields.size()];
for (int i=0; i<queryFields.size(); i++) {
String field = queryFields.get(i);
if ("objs".equals(field)) {
List<String> objSet = getParam("objs");
objsLen = objSet.size();
filters[i] = Filters.in("objs", objSet);
} else {
switch (DataType.toData(dataTypeMap.get(field).toUpperCase())) {
case LONG :
filters[i] = Filters.eq(field, Long.parseLong(getParam(field).toString()));
break;
case DOUBLE :
filters[i] = Filters.eq(field, Double.parseDouble(getParam(field).toString()));
break;
case INT :
filters[i] = Filters.eq(field, Integer.parseInt(getParam(field).toString()));
break;
default :
filters[i] = Filters.eq(field, getParam(field));
}
}
}
// 生成查询列名
Bson[] projections = new Bson[2];
fidSet = getParam("fids");
projections[0] = Projections.include(new ArrayList<String>(fidSet));
projections[1] = Projections.include(queryFields);
// 查询mongo
FindIterable<Document> iter = collection.find(Filters.and(filters)).projection(Projections.fields(projections));
final Map<String, JSONArray> map = new HashMap<String, JSONArray>();
iter.forEach(new Block<Document>() {
public void apply(Document doc) {
for (String seqid : seqMap.keySet()) {
Set<String> fidSet = seqMap.get(seqid);
JSONObject object = new JSONObject();
object.put("objs", doc.get("objs"));
for (String fid : fidSet) {
if (fid.indexOf("#") > -1) {
object.put(fid.split("#")[0], doc.get(fid));
} else {
object.put(fid, doc.get(fid));
}
}
if (map.containsKey(seqid)) {
JSONArray array = map.get(seqid);
array.add(object);
} else {
JSONArray array = new JSONArray();
array.add(object);
map.put(seqid, array);
}
}
}
});
原文地址:
http://blog.csdn.net/autfish/article/details/51366839