java mongodb3.2 find_MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询

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 {

//根据实际环境修改ip和端口

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 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 iterable = mc.find();

printResult("find all", iterable);

//TODO: 将在这里填充更多查询示例

}

//打印查询的结果集

public void printResult(String doing, FindIterable iterable) {

System.out.println(doing);

iterable.forEach(new Block() {

public void apply(final Document document) {

System.out.println(document);

}

});

System.out.println("------------------------------------------------------");

System.out.println();

}

}

如上面代码所示,把所有的查询操作集中在show()方法中演示,并且在执行后打印结果集以观察查询结果。下面来填充show()方法

注意需要静态导入

import static com.mongodb.client.model.Filters.*;

import static com.mongodb.client.model.Projections.*;

import static com.mongodb.client.model.Sorts.*;

//创建单字段索引

mc.createIndex(new Document("words", 1));

//创建组合索引(同样遵循最左前缀原则)

mc.createIndex(new Document("title", 1).append("owner", -1));

//创建全文索引

mc.createIndex(new Document("title", "text"));

//查询全部

FindIterable iterable = mc.find();

printResult("find all", iterable);

//查询title=good

iterable = mc.find(new Document("title", "good"));

printResult("find title=good", iterable);

//查询title=good and owner=tom

iterable = mc.find(new Document("title", "good").append("owner", "tom"));

printResult("find title=good and owner=tom", iterable);

//查询title like %good% and owner=tom

iterable = mc.find(and(regex("title", "good"), eq("owner", "tom")));

printResult("find title like %good% and owner=tom", iterable);

//查询全部按title排序

iterable = mc.find().sort(ascending("title"));

printResult("find all and ascending title", iterable);

//查询全部按owner,title排序

iterable = mc.find().sort(ascending("owner", "title"));

printResult("find all and ascending owner,title", iterable);

//查询全部按words倒序排序

iterable = mc.find().sort(descending("words"));

printResult("find all and descending words", iterable);

//查询owner=tom or words>350

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);

//返回title和owner字段

iterable = mc.find().projection(include("title", "owner"));

printResult("find all include (title,owner)", iterable);

//返回除title外的其他字段

iterable = mc.find().projection(exclude("title"));

printResult("find all exclude title", iterable);

//不返回_id字段

iterable = mc.find().projection(excludeId());

printResult("find all excludeId", iterable);

//返回title和owner字段且不返回_id字段

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);

//一个错误的示例, 想查询评论中包含作者是white且分值>2的, 返回结果不符合预期

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);

//查找title以good开头的, 并且comments只保留一个元素

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);

//用Filters构建的title=good

iterable = mc.find(eq("title", "good"));

printResult("Filters: title eq good", iterable);

//$in 等同于sql的in

iterable = mc.find(in("owner", "joe", "john", "william"));

printResult("Filters: owner in joe,john,william", iterable);

//$nin 等同于sql的not in

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);

//$ne 不等于

iterable = mc.find(ne("words", 300));

printResult("Filters: words ne 300", iterable);

//$and 组合条件

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);

//查询第2个元素值为2的数组

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);

//$exists

iterable = mc.find(exists("tag"));

printResult("Filters: exists tag", iterable);

iterable = mc.find(type("words", BsonType.INT32));

printResult("Filters: type words is int32", iterable);

这里列出的查询方式可以覆盖到大部分开发需求,更多查询需求请参考官方文档。

(完)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MongoDB是一种基于文档的数据库,使用BSON(二进制JSON)格式来存储和查询数据。它是开源的,使用C++编写,但也提供了Java驱动程序,使Java开发人员可以方便地与MongoDB进行交互。 Java驱动程序是MongoDB的官方驱动程序之一,它提供了一组API,使Java开发人员可以轻松地连接和操作MongoDB。在这篇文章中,我们将深入探讨Java驱动程序如何连接MongoDB,以及Java驱动程序的源代码如何实现这些功能。 首先,我们需要在Java应用程序中引入MongoDBJava驱动程序。可以在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.7</version> </dependency> ``` 接下来,我们需要创建一个MongoClient对象来连接MongoDB。MongoClient对象是Java驱动程序中用于连接MongoDB的核心类之一。以下是创建MongoClient对象的示例代码: ```java import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; public class MongoDBConnection { public static void main(String[] args) { MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017"); MongoClient mongoClient = new MongoClient(uri); } } ``` 在这个例子中,我们使用MongoClientURI类来指定MongoDB的连接字符串。连接字符串包含MongoDB的主机名和端口号。然后,我们使用MongoClient类创建一个连接MongoDB的客户端对象。现在,我们已经成功地连接到MongoDB,接下来我们可以使用Java驱动程序来操作MongoDB中的数据了。 Java驱动程序提供了一组API,使Java开发人员可以与MongoDB进行交互。以下是一些常用的API: - MongoDatabase:表示MongoDB中的数据库。 - MongoCollection:表示MongoDB中的集合。 - Document:表示MongoDB中的文档。 以下是使用Java驱动程序查询MongoDB中数据的示例代码: ```java import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class MongoDBQuery { public static void main(String[] args) { MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017"); MongoClient mongoClient = new MongoClient(uri); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("users"); MongoCursor<Document> cursor = collection.find().iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); System.out.println(doc.toJson()); } cursor.close(); mongoClient.close(); } } ``` 在这个例子中,我们使用MongoDatabase和MongoCollection类来获取MongoDB中的数据库和集合。然后,我们使用MongoCollection类中的find()方法来查询集合中的所有文档。最后,我们使用MongoCursor类来遍历查询结果,并使用Document类来表示MongoDB中的文档。 这就是Java驱动程序连接MongoDB的基本原理。Java驱动程序提供了一组简单易用的API,使Java开发人员可以轻松地与MongoDB进行交互。如果您想深入了解Java驱动程序的工作原理,可以查看Java驱动程序的源代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值