MongoDB学习笔记(十)——JAVA整合MongoDB:MongoDB Java Driver、spring-data-mongodb:mongoTemplate

本篇博文本来是打算在上一篇的当成其一部分写的。但是后来想了下还是另起一篇博文。

该篇博文主要是介绍Java整合MongoDB,因为接下来讲MongoDB 的操作内容等的我会根据shell(因为服务器上的操作和shell一样这里就不讲了)、MongoDB Compass、java driver(mongo的java驱动)、mongoTemplate几个方面来测试,所以这里就先讲一下MongoDB Java Driver、spring-data-mongodb的概念和一些基础。

注:由于编辑器的原因,<>在博文中和表格中会隐藏其括起来的内容,所以我讲<>符号替换为《》,请谅解!
另 因为篇幅的原因,内部提供的方法没有标识其返回值类型,若各位想看其返回值,请看它所属对象的官方文档

MongoDB Java Driver

注:该驱动器在3.0版本有一个很大的改动,导致以前的很多东西遭到弃用,网上暂时没有系统的学习博文或文档,所以只能自己整理,比较麻烦,所以下面的东西可能比较乱,当然如果有问题请大家及时联系我,以便改正
另,下方提供的文档都是3.6版本的文档内容,如果大家想看最新版本的大家可以复制链接,将链接的版本号改下应该就可以了。这个我没有试过

MongoDB的java驱动程序主要时在java中实现MongoDB,我们如果在java应用程序中访问和使用MongoDB,需要使用该驱动程序,java MongoDB驱动程序程序是一个库,提供了java应用程序中访问MongoDB服务器所需的对象和功能。详细的大家可以看java MongoDB驱动程序的官方文档

在此篇博文主要介绍一下驱动程序中的对象。具体的操作可以参考后面的操作演示:

整合

我们想要在我们的项目中使用MongoDB的java驱动,我们需要引用一个jar包。

发行版中有两个Maven引用。新应用程序的首选引用是mongodb-driver,但是,MongoDB仍然发布了传统的mongo-java-driveruber-jar。

MongoDB Driver

MongoDB驱动程序mongodb-driver是同步更新的Java驱动程序,它包含传统API以及符合新的跨驱动程序(cross-driver)CRUD规范的新的通用MongoCollection接口。

注:mongodb-driver不是OSGi包:mongodb-drivermongodb-driver-coremongodb-driver的依赖)都是com.mongodb包中的类。 对于基于OSGi的应用程序,请改用mongo-java-driver uber-jar。

你也可以在 这里手动下载载最新的 mongodb-driver
如果手动下载 mongodb-driver,您还必须下载其依赖项: bsonmongodb-driver-core

Uber Jar(Legacy)

对于新的应用程序,首选的引用是mongodb-driver;然而,传统的mongo-java-driverUber Jar仍然可用。 uber jar包含:BSON库,核心库和mongodb-driver

注:mongo-java-driver引用是一个有效的OSGi软件包。

你也可以在这里手动下载载最新的mongo-java-driver

下面时两个jar包的maven引用

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.6.3</version>
    </dependency>
</dependencies>
<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.6.3</version>
    </dependency>
</dependencies>

快速开始

如果大家想快速的了解MongoDB 的驱动程序的开发,大家可以参考他们的官方文档的Quick Start,内部有关于驱动程序的大致功能的一些演示,不过内部的内容都是比较少的。但是可以帮助我们大致了解它的功能以及如何运用。

MongoClient

java对象MongoClient提供了连接到MongoDB服务器和访问数据库的功能。要在java应用程序中实现MongoDB,首先需要创建一个MongoClient对象实例,然后就可以使用它来访问数据库、设置写入关注以及执行其他操作。

要创建MongoClient对象实例,需要从驱动中导入它,再使用合适的选项调用new MongoClient(),如下:

MongoClient client = new MongoClient("localhost",27017);

创建MongoClient实例后,就可以使用其方法来访问数据库和设置选项:

下方是MongoClient的构造方法表和其提供的方法以及其继承的方法,大家可以参考MongoClient的官方文档,其中弃用的我就不写了

方法 功能描述
MongoClient() 基于(单个)mongodb节点(localhost,默认port)创建实例。
MongoClient(List《ServerAddress》 seeds) 根据副本集成员或mongos服务器的列表创建实例。
MongoClient(List《ServerAddress》 seeds, MongoClientOptions options) 根据副本集成员或mongos服务器的列表创建实例。
MongoClient(List《ServerAddress》 seeds, MongoClientOptions options) 基于副本集成员或mongos服务器列表构建实例。
MongoClient(List《ServerAddress》 seeds, MongoCredential credential, MongoClientOptions options) 根据副本集成员或mongos服务器的列表创建实例。
MongoClient(List《ServerAddress》 seeds, MongoCredential credential, MongoClientOptions options, MongoDriverInformation mongoDriverInformation) 创建一个MongoClient
MongoClient(MongoClientURI uri) 创建一个由URI描述的Mongo。
MongoClient(MongoClientURI uri, MongoDriverInformation mongoDriverInformation) 创建一个由URI描述的Mongo。
MongoClient(ServerAddress addr) 基于(单个)mongodb节点创建Mongo实例
MongoClient(ServerAddress addr, MongoClientOptions options) 使用给定的ServerAddress和默认选项创建基于(单个)mongo节点的Mongo实例。
MongoClient(ServerAddress addr, MongoCredential credential, MongoClientOptions options) 使用给定的服务器地址,凭证和选项创建基于(单个)mongo节点的Mongo实例
MongoClient(ServerAddress addr, MongoCredential credential, MongoClientOptions options, MongoDriverInformation mongoDriverInformation) 使用给定的ServerAddress创建一个到单个节点的MongoClient。
MongoClient(String host) 基于(单个)mongodb节点创建Mongo实例。
MongoClient(String host, int port) 基于(单个)mongodb节点创建Mongo实例。
MongoClient(String host, MongoClientOptions options) 基于(单个)mongodb节点(默认端口)创建Mongo实例。
自己提供方法总结
getCredentialsList() 通过身份验证获取此客户端所有连接的凭证列表
getDefaultCodecRegistry() 获取默认编解码器注册表。
getDatabase(String databaseName) 获取数据库对象
getMongoClientOptions() 获取此客户端用于连接到服务器的选项。
listDatabaseNames() 获取数据库名称列表
listDatabaseNames(ClientSession clientSession) 获取数据库名称列表
listDatabases() 获取数据库列表
listDatabases(Class《T》 clazz) 获取数据库列表
listDatabases(ClientSession clientSession) 获取数据库列表
listDatabases(ClientSession clientSession, Class《T》 clazz) 获取数据库列表
startSession(ClientSessionOptions options) 创建客户端session。
继承自com.mongodb.Mongo方法 com.mongodb.Mongo官方文档
继承自Object方法 clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

注:由于篇幅原因,每个方法的详细解释不便在这里描述,请大家查看官方文档

MongoDatabase–DB

DB对象提供了身份验证、用户账号管理以及访问和操作集合的功能。要获取DB对象实例,最简单的方法是调用MongoClient对象的getDB()方法。大家可以参考DB的官方文档

MongoClient client= new MongoClient("localhost",27017);
DB db = client.getDB("dbName");

DB, DBCollection和DBCursor对象从3.0开始已经不建议使用,被MongoDB弃用,但是为了保证以前版本的可用性,还没有正式弃用,DB对象可以使用MongoDatabase对象代替。所以这里就不仔细讲解DB对象了。下面讲解下MongoDatabase对象(官方文档):

MongoDatabase对象和DB功能一致,提供了身份验证、用户账号管理以及访问和操作集合的功能。
获取MongoDatabase实例的方法和DB的差不多,我们可以使用MongoClient.getDatabase()获取,如:

 MongoDatabase database = mongoClient.getDatabase("mydb");

获取到MongoDatabase 实例后我们可以调用其方法:

方法 功能描述
createCollection(ClientSession clientSession, String collectionName) 用给定的名称创建一个新的集合。
createCollection(ClientSession clientSession, String collectionName, CreateCollectionOptions createCollectionOptions) 使用所选选项创建新集合
createCollection(String collectionName) 用给定的名称创建一个新的集合。
createCollection(String collectionName, CreateCollectionOptions createCollectionOptions) 用选定的选项创建一个新的集合
createView(ClientSession clientSession, String viewName, String viewOn, List pipeline) 创建一个具有给定名称、支持集合/视图名称的视图以及定义视图的聚合管道。
createView(ClientSession clientSession, String viewName, String viewOn, List pipeline, CreateViewOptions createViewOptions) 创建一个具有给定名称、支持集合/视图名称、聚合管道以及定义视图的选项的视图。
createView(String viewName, String viewOn, List pipeline) 创建一个具有给定名称、支持集合/视图名称的视图以及定义视图的聚合管道。
createView(String viewName, String viewOn, List pipeline, CreateViewOptions createViewOptions) 创建一个具有给定名称、支持集合/视图名称、聚合管道以及定义视图的选项的视图。
drop() 删除当前数据库
drop(ClientSession clientSession) 删除当前数据库
getCodecRegistry() 获取MongoDatabase的编解码器注册表。
getCollection(String collectionName) 根据指定名称获取集合
getCollection(String collectionName, Class《TDocument》 documentClass) 获取具有特定默认文档类的集合。
getName() 获取数据库的名称
getReadConcern() 获取MongoDatabase对象的读取关注程度
getReadPreference() 获取MongoDatabase对象的的读取偏好。
getWriteConcern() 获取MongoDatabase对象的写入关注程度
listCollectionNames() 获取此数据库中所有集合的名称。
listCollectionNames(ClientSession clientSession) 获取此数据库中所有集合的名称。
listCollections() 查找此数据库中的所有集合。
listCollections(Class《TResult》 resultClass) 查找此数据库中的所有集合。
listCollections(ClientSession clientSession) 查找此数据库中的所有集合。
listCollections(ClientSession clientSession, Class《TResult》 resultClass) 查找此数据库中的所有集合。
runCommand(Bson command) 使用ReadPreference.primary()的读取偏好在当前数据库的上下文中执行给定的命令。
runCommand(Bson command, Class《TResult》 resultClass) 使用ReadPreference.primary()的读取偏好在当前数据库的上下文中执行给定的命令。
runCommand(Bson command, ReadPreference readPreference) 用给定的读取偏好在当前数据库的上下文中执行给定的命令。
runCommand(Bson command, ReadPreference readPreference, Class《TResult》 resultClass) 用给定的读取偏好在当前数据库的上下文中执行给定的命令。
runCommand(ClientSession clientSession, Bson command) 使用ReadPreference.primary()的读取偏好在当前数据库的上下文中执行给定的命令。
runCommand(ClientSession clientSession, Bson command, Class《TResult》 resultClass) 使用ReadPreference.primary()的读取偏好在当前数据库的上下文中执行给定的命令
runCommand(ClientSession clientSession, Bson command, ReadPreference readPreference) 用给定的读取偏好在当前数据库的上下文中执行给定的命令。
runCommand(ClientSession clientSession, Bson command, ReadPreference readPreference, Class《TResult》 resultClass) 用给定的读取偏好在当前数据库的上下文中执行给定的命令。
withCodecRegistry(CodecRegistry codecRegistry) 使用不同的编解码器注册表创建一个新的MongoDatabase实例。
withReadConcern(ReadConcern readConcern) 用不同的阅读关注创建一个新的MongoDatabase实例。
withReadPreference(ReadPreference readPreference) 使用不同的读取偏好创建一个新的MongoDatabase实例。
withWriteConcern(WriteConcern writeConcern) 用不同的写入关注创建一个新的MongoDatabase实例。

注:上述方法很多功能描述一致,但是其适用场合不同,具体的请看上面的官方文档链接

MongoCollection – DBCollection

MongoCollection 和 DBCollection实例都提供了访问和操作集合中文档的功能。

若要获取MongoCollection 实例,可以使用MongoDatabase实例的getCollection()
若要获取DBCollection实例,可以使用DB实例的getCollection()

和MongoDatabase–DB一样,DBCollection已经从3.0版本以后弃用了,为了以前版本的MongoDB,现在还没有完全舍弃,现在使用MongoCollection来代替。所以这里就不讲DBCollection对象的方法了,只列取MongoCollection对象的方法。

注:MongoCollection不会破坏二进制兼容性。

MongoCollection是通用的,允许不同的类型来表示文档。任何自定义类都必须在CodecRegistry中注册一个编解码器。默认的CodecRegistry包含内置的支持:BsonDocument,Document和DBObject。

方法 功能描述
aggregate(ClientSession clientSession, List pipeline) 根据指定的聚合管道汇总文档。
aggregate(ClientSession clientSession, List pipeline, Class《TResult》 resultClass) 根据指定的聚合管道汇总文档。
aggregate(List pipeline) 根据指定的聚合管道汇总文档。
aggregate(List pipeline, Class《TResult》 resultClass) 根据指定的聚合管道汇总文档。
bulkWrite(ClientSession clientSession, List> requests) 执行插入,更新,替换和删除的组合操作。
bulkWrite(ClientSession clientSession, List> requests, BulkWriteOptions options) 执行插入,更新,替换和删除的组合操作。
bulkWrite(List> requests) 执行插入,更新,替换和删除的组合操作。
bulkWrite(List> requests, BulkWriteOptions options) 执行插入,更新,替换和删除的组合操作。
count() 统计集合中的文档数量。
count(Bson filter) 根据给定的条件计算集合中文档的数量。
count(Bson filter, CountOptions options) 根据给定的条件计算集合中文档的数量。
count(ClientSession clientSession) 统计集合中的文档数量。
count(ClientSession clientSession, Bson filter) 根据给定的条件计算集合中文档的数量。
count(ClientSession clientSession, Bson filter, CountOptions options) 根据给定的条件计算集合中文档的数量。
createIndex(Bson keys) 在给定的键上创建一个索引。
createIndex(Bson keys, IndexOptions indexOptions) 用给定的键和选项创建一个索引。
createIndex(ClientSession clientSession, Bson keys) 用给定的键创建一个索引。
createIndex(ClientSession clientSession, Bson keys, IndexOptions indexOptions) 用给定的键和选项创建一个索引。
createIndexes(ClientSession clientSession, List《IndexModel》 indexes) 创建多个索引。
createIndexes(ClientSession clientSession, List《IndexModel》 indexes, CreateIndexOptions createIndexOptions) 创建多个索引。
createIndexes(List《IndexModel》 indexes) 创建多个索引。
createIndexes(List《IndexModel》 indexes, CreateIndexOptions createIndexOptions) 创建多个索引。
deleteMany(Bson filter) 删除集合中与给定查询过滤器匹配的所有文档。
deleteMany(Bson filter, DeleteOptions options) 删除集合中与给定查询过滤器匹配的所有文档。
deleteMany(ClientSession clientSession, Bson filter) 删除集合中与给定查询过滤器匹配的所有文档。
deleteMany(ClientSession clientSession, Bson filter, DeleteOptions options) 删除集合中与给定查询过滤器匹配的所有文档。
deleteOne(Bson filter) 从集合中删除至多一个与给定过滤器匹配的文档。
deleteOne(Bson filter, DeleteOptions options) 从集合中删除至多一个与给定过滤器匹配的文档。
deleteOne(ClientSession clientSession, Bson filter) 从集合中删除至多一个与给定过滤器匹配的文档。
deleteOne(ClientSession clientSession, Bson filter, DeleteOptions options) 从集合中删除至多一个与给定过滤器匹配的文档。
distinct(ClientSession clientSession, String fieldName, Bson filter, Class《TResult》 resultClass) 获取指定字段名称的不同值。
distinct(ClientSession clientSession, String fieldName, Class《TResult》 resultClass)) 获取指定字段名称的不同值。
distinct(String fieldName, Bson filter, Class《TResult》 resultClass)) 获取指定字段名称的不同值。
distinct(String fieldName, Class《TResult》 resultClass)) 获取指定字段名称的不同值。
drop() 从当前数据库删除当前集合
drop(ClientSession clientSession) 从当前数据库删除当前集合
dropIndex(Bson keys) 删除指定键上的索引
dropIndex(Bson keys, DropIndexOptions dropIndexOptions) 删除指定键上的索引
dropIndex(ClientSession clientSession, Bson keys) 删除指定键上的索引
dropIndex(ClientSession clientSession, Bson keys, DropIndexOptions dropIndexOptions) 删除指定键上的索引
dropIndex(ClientSession clientSession, String indexName) 删除给定名称的索引
dropIndex(ClientSession clientSession, String indexName, DropIndexOptions dropIndexOptions) 删除给定名称的索引
dropIndex(String indexName) 删除给定名称的索引
dropIndex(String indexName, DropIndexOptions dropIndexOptions) 删除给定名称的索引
dropIndexes() 删除此集合上除_id上以外的所有索引
dropIndexes(ClientSession clientSession) 删除此集合上除_id上以外的所有索引
dropIndexes(ClientSession clientSession, DropIndexOptions dropIndexOptions) 删除此集合上除_id上以外的所有索引
dropIndexes(DropIndexOptions dropIndexOptions) 删除此集合上除_id上以外的所有索引
find() 查找集合中的所有文档。
find(Bson filter)) 查找集合中的所有文档。
find(Bson filter, Class《TResult》 resultClass)) 查找集合中的所有文档。
find(Class《TResult》 resultClass)) 查找集合中的所有文档。
find(ClientSession clientSession)) 查找集合中的所有文档。
find(ClientSession clientSession, Bson filter)) 查找集合中的所有文档。
find(ClientSession clientSession, Bson filter, Class《TResult》 resultClass)) 查找集合中的所有文档。
find(ClientSession clientSession, Class《TResult》 resultClass)) 查找集合中的所有文档。
findOneAndDelete(Bson filter) 以原子方式查找文档并将其删除。
findOneAndDelete(Bson filter, FindOneAndDeleteOptions options) 以原子方式查找文档并将其删除。
findOneAndDelete(ClientSession clientSession, Bson filter) 以原子方式查找文档并将其删除。
findOneAndDelete(ClientSession clientSession, Bson filter, FindOneAndDeleteOptions options) 以原子方式查找文档并将其删除。
findOneAndReplace(Bson filter, TDocument replacement) 以原子方式查找文档并将其删除。
findOneAndReplace(Bson filter, TDocument replacement, FindOneAndReplaceOptions options) 以原子方式查找文档并将其删除。
findOneAndReplace(ClientSession clientSession, Bson filter, TDocument replacement) 以原子方式查找文档并将其删除。
findOneAndReplace(ClientSession clientSession, Bson filter, TDocument replacement, FindOneAndReplaceOptions options) 以原子方式查找文档并将其删除。
findOneAndUpdate(Bson filter, Bson update) 以原子方式查找文档并将其删除。
findOneAndUpdate(Bson filter, Bson update, FindOneAndUpdateOptions options) 以原子方式查找文档并将其删除。
findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update) 以原子方式查找文档并将其删除。
findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update, FindOneAndUpdateOptions options) 以原子方式查找文档并将其删除。
getCodecRegistry() 获取MongoCollection的编解码器注册表
getDocumentClass() 获取存储在此集合中的文档类。
getNamespace() 获取当前集合的命名空间
getReadConcern() 获取关于MongoCollection的阅读关注程度。
getReadPreference() 获取MongoCollection的读取偏好。
getWriteConcern() 获得关于MongoCollection的写入关注程度。
insertMany(ClientSession clientSession, List documents) 插入一个或多个文档
insertMany(ClientSession clientSession, List documents, InsertManyOptions options) 插入一个或多个文档
insertMany(List documents) 插入一个或多个文档
insertMany(List documents, InsertManyOptions options) 插入一个或多个文档
insertOne(ClientSession clientSession, TDocument document) 插入给定的文档
insertOne(ClientSession clientSession, TDocument document, InsertOneOptions options) 插入给定的文档
insertOne(TDocument document) 插入给定的文档
insertOne(TDocument document, InsertOneOptions options) 插入给定的文档
listIndexes() 获取此集合中的所有索引。
listIndexes(Class《TResult》 resultClass) 获取此集合中的所有索引。
listIndexes(ClientSession clientSession) 获取此集合中的所有索引。
listIndexes(ClientSession clientSession, Class《TResult》 resultClass) 获取此集合中的所有索引。
mapReduce(ClientSession clientSession, String mapFunction, String reduceFunction) 根据指定的map-reduce函数汇总文档。
mapReduce(ClientSession clientSession, String mapFunction, String reduceFunction, Class《TResult》 resultClass) 根据指定的map-reduce函数汇总文档。
mapReduce(String mapFunction, String reduceFunction) 根据指定的map-reduce函数汇总文档。
mapReduce(String mapFunction, String reduceFunction, Class《TResult》 resultClass) 根据指定的map-reduce函数汇总文档。
renameCollection(ClientSession clientSession, MongoNamespace newCollectionNamespace) 将oldCollectionName的集合重命名为newCollectionName。
renameCollection(ClientSession clientSession, MongoNamespace newCollectionNamespace, RenameCollectionOptions renameCollectionOptions) 将oldCollectionName的集合重命名为newCollectionName。
renameCollection(MongoNamespace newCollectionNamespace) 将oldCollectionName的集合重命名为newCollectionName。
renameCollection(MongoNamespace newCollectionNamespace, RenameCollectionOptions renameCollectionOptions) 将oldCollectionName的集合重命名为newCollectionName。
replaceOne(Bson filter, TDocument replacement) 根据指定的参数替换集合中的文档。
replaceOne(Bson filter, TDocument replacement, UpdateOptions updateOptions) 根据指定的参数替换集合中的文档。
replaceOne(ClientSession clientSession, Bson filter, TDocument replacement) 根据指定的参数替换集合中的文档。
replaceOne(ClientSession clientSession, Bson filter, TDocument replacement, UpdateOptions updateOptions) 根据指定的参数替换集合中的文档。
updateMany(Bson filter, Bson update) 根据指定的参数替换集合中的文档。
updateMany(Bson filter, Bson update, UpdateOptions updateOptions) 根据指定的参数替换集合中的文档。
updateMany(ClientSession clientSession, Bson filter, Bson update) 根据指定的参数替换集合中的文档。
updateMany(ClientSession clientSession, Bson filter, Bson update, UpdateOptions updateOptions) 根据指定的参数替换集合中的文档。
updateOne(Bson filter, Bson update) 根据指定的参数替换集合中的单个文档。
updateOne(Bson filter, Bson update, UpdateOptions updateOptions) 根据指定的参数替换集合中的单个文档。
updateOne(ClientSession clientSession, Bson filter, Bson update) 根据指定的参数替换集合中的单个文档。
updateOne(ClientSession clientSession, Bson filter, Bson update, UpdateOptions updateOptions) 根据指定的参数替换集合中的单个文档。
watch() 为此集合创建更改流。
watch(Class《TResult》 resultClass) 为此集合创建更改流。
watch(ClientSession clientSession) 为此集合创建更改流。
watch(ClientSession clientSession, Class《TResult》 resultClass) 为此集合创建更改流。
watch(ClientSession clientSession, List pipeline) 为此集合创建更改流。
watch(ClientSession clientSession, List pipeline, Class《TResult》 resultClass) 为此集合创建更改流。
watch(List pipeline) 为此集合创建更改流。
watch(List pipeline, Class《TResult》 resultClass) 为此集合创建更改流。
withCodecRegistry(CodecRegistry codecRegistry) 用不同的编解码器注册表创建一个新的MongoCollection实例。
withDocumentClass(Class《NewTDocument》 clazz) 用不同的默认类创建一个新的MongoCollection实例,将从数据库返回的任何文档转换为..
withReadConcern(ReadConcern readConcern) 用不同的读取关注创建一个新的MongoCollection实例。
withReadPreference(ReadPreference readPreference) 使用不同的读取偏好创建一个新的MongoCollection实例。
withWriteConcern(WriteConcern writeConcern) 用不同的写入关注创建一个新的MongoCollection实例。

FindIterable《TResult》– DBCursor

FindIterable《TResult》和DBCursor都是MongoDB的find()方法返回的对象,不过一个是3.0以后的返回对象,一个是3.0版本以前的对象。表示MongoDB服务器中的一组文档,使用查找操作查询集合时,通常返回一个FindIterable《TResult》\DBCursor对象,而不是向Java应用程序返回全部的文档对象,这让您能够以受控制的方式访问文档。可以参考官方文档

FindIterable《TResult》\DBCursor对象以分批的方式从服务器取回文档,并使用一个索引来迭代文档,在迭代期间,当索引到达当前那批文档末尾时,将从服务器取回下批文档。也就是说,如果一个查询查询出的结果是100条数据,但是java返回的MongoCursor\DBCursor对象可能只包含20个文档,当我们遍历这20个文档时,遍历到最后它会自动从服务器取出第21-40的文档。

注:原先我以为DBCursor对象的替换对象是MongoCursor,但是我看了MongoCursor对象的介绍以及其提供的方法,发现这是不准确的,后来我从MongoCollection的官方文档看到其提供的find()方法,返回的是FindIterable《TResult》,才发现DBCursor的替代品是FindIterable《TResult》,后来发现还是不对,其实DBCursor的替代品是FindIterable《TResult》 + MongoCursor两个的组合,DBcursor中包含了FindIterable和MongoCursor的方法。只不过MongoCursor迭代器的一些操作方法抽取了出来。我们可以通过FindIterable的iterator()方法来获取MongoCursor,并且通过MongoCursor的hasNext()等方法迭代结果。

对于FindIterable《TResult》\DBCursor对象的获取,也都是差不多,
获取FindIterable《TResult》对象,需要获取到MongoCollection对象,调用其find():

FindIterable<TDocument> iter = collection.find([....])

获取DBCursor对象,需要获取到DBCollection对象,调用其find():

DBCursor cursor= collection.find([....])
方法 功能描述
batchSize(int batchSize) 设置每批中返回的文档数。
collation(Collation collation) 设置排序选项
comment(String comment) 给查询设置注释
cursorType(CursorType cursorType) 设置游标类型
filter(Bson filter) 设置查询过滤器以应用于查询。
hint(Bson hint) 设置要使用哪个索引的提示。
limit(int limit) 设置应用的限制。
max(Bson max) 设置指定索引的特定上限。
maxAwaitTime(long maxAwaitTime, java.util.concurrent.TimeUnit timeUnit) 设置服务器等待可移动游标查询新文档的最长时间。这仅适用于TAILABLE_AWAIT游标。当光标不是TAILABLE_AWAIT游标时,该选项将被忽略
maxScan(long maxScan) 设置执行查询时扫描的文档或索引键的最大数量。
maxTime(long maxTime, java.util.concurrent.TimeUnit timeUnit) 为此操作设置服务器上的最长执行时间。
min(Bson min) 设置指定索引的特定下限。
noCursorTimeout(boolean noCursorTimeout) 闲置时间(10分钟)后,服务器通常会暂停空闲游标,以防止使用过量的内存。
oplogReplay(boolean oplogReplay) 用户在正常情况下不应该设置它。
partial(boolean partial) 如果一个或多个分片无法访问(而不是引发错误),则从分片群集获取部分结果。
projection(Bson projection) 设置为所有匹配文档返回的字段的描述文档。
returnKey(boolean returnKey) 设置returnKey。
showRecordId(boolean showRecordId) 设置showRecordId。
skip(int skip) 设置跳过的文档数。
snapshot(boolean snapshot) 设置snapshot。
sort(Bson sort) 设置用于应用于查询的排序条件

BasicDBObject、DBObject、Bson

首先讲一下这三者在3.6版本的关系:

BasicDBObject实现的接口:DBObject, java.io.Serializable, Cloneable, java.util.Map, BSONObject, Bson

DBObject所有已知的实现类:BasicDBList, BasicDBObject, CommandResult, GridFSDBFile, GridFSFile, GridFSInputFile, LazyDBList, LazyDBObject, ReflectionDBObject
Bson所有已知实现类:BasicDBObject, BsonDocument, BsonDocumentWrapper, CommandResult, Document, RawBsonDocument

所以上面的关系大概可以用下图表示:
这里写图片描述

下面来讲一下这三个对象:

首先讲一下最重要的BasicDBObject,我们前面的很多关于数据库、集合、游标的操作都将对象作为参数。这些对象定义了查询、排序、聚合以及其他运算符。文档也是以对象的方式从数据库返回的。

在shell中,这些对象时JavaScript对象,但在java中,表示文档和请求参数的对象都是特殊对象。服务器返回的文档3.6以前是用DBObject对象表示的,3.6版本新增TDocument来表示,提供了获取和设置文档中字段的功能,对于用作请求参数的对象,是用BasicDBObject表示的。

也就是说BasicDBObject是MongoDB数据库在java中的查询条件等的实现对象,使用该对象,你可以设置查询、排序、聚合等其他运算条件。

获取该对象可以使用下方的构造方法创建。
给BasicDBObject对象添加属性,可以使用append().

例:假如您要创建一个查询条件对象,用于查询第一个字母为a且长度超过6的单词,在shell中可以使用如下代码:

find({"first":"a","size":{"$gt":6}})

而在java中,必须使用一下语法创建一个将传递给方法find()的BasicDBObject对象:

BasicDBObject query = new BasicDBObject("first","a");
query.append("size",new BasicDBObject("$gt",6));
mycollection.find(query);

使用这种方式,可创建需要传递给MongoDB数据库请求的对象。

从DBCollection和 MongoCollection对象提供的方法中我们可以看到一个现象就是,他们提供的方法需要传入的各种条件是要求传入DBObject或Bson的。而上面说的是传入BasicDBObject ,这和文档是没有矛盾的,因为BasicDBObject是DBObject和Bson的实现类。是可以传入的。

BasicDBObject提供了一些方法:

方法 功能描述
BasicDBObject() 创建一个空对象
BasicDBObject(int size) 创建一个空对象,size为估计要插入的字段数量
BasicDBObject(Map map) 使用给定map创建一个对象
BasicDBObject(String key, Object value) 用给定的键/值创建一个对象
append(String key, Object val) 向此对象添加键/值对
copy() 创建一个新的实例,该实例是此BasicDBObject的副本。
isPartialObject() 无论markAsPartialObject()是否曾经被调用过,只有当你打算upsert并且不想冒失去字段的风险时才有关系。
markAsPartialObject() 如果仅使用某些字段检索此对象(使用字段过滤器),则将调用此方法以将其标记
parse(String json) 将MongoDB扩展JSON格式的字符串解析为BasicDBObject。
parse(String json, Decoder《BasicDBObject》 decoder) 将MongoDB扩展JSON格式的字符串解析为BasicDBObject。
toBsonDocument(Class《TDocument》 documentClass, CodecRegistry codecRegistry) 将筛选器呈现为BsonDocument。
toJson() 使用JsonMode.STRICT输出模式获取此文档的JSON表示,否则为JsonWriterSettings.Builder和DBObjectCodec的默认设置。
toJson(Encoder《BasicDBObject》 encoder) 获取此文档的json表示形式
toJson(JsonWriterSettings writerSettings) 获取此文档的json表示形式
toJson(JsonWriterSettings writerSettings, Encoder《BasicDBObject》 encoder) 获取此文档的json表示形式
toString() 返回此对象的json序列化

BasicDBObject提供了一些方法:

方法 功能描述
isPartialObject()
markAsPartialObject() 如果仅使用某些字段检索此对象(使用字段过滤器),则将调用此方法以将其标记
从org.bson.BSONObject继承方法 containsField, containsKey, get, keySet, put, putAll, putAll, removeField, toMap

Bson提供了一些方法:

方法 功能描述
toBsonDocument(Class《TDocument》 documentClass, CodecRegistry codecRegistry) 将筛选器呈现为BsonDocument

spring-data-mongodb:mongoTemplate

上面讲了MongoDB提供的整合java的原生驱动MongoDB Java Driver,而使用Spring项目时,我们可以使用Spring提供给我们封装的一个jar包:spring-data-mongodb

Spring Data其实是一个高级别的Spring Source项目,而Spring Data MongoDB仅仅是其中的一个子项目。Spring Data旨在为关系型数据库、非关系型数据、Map-Reduce框架、云数据服务等等提供统一的数据访问API。
无论是哪种持久化存储, 数据访问对象(或称作为DAO,即Data Access Objects)通常都会提供对单一域对象的CRUD (创建、读取、更新、删除)操作、查询方法、排序和分页方法等。Spring Data则提供了基于这些层面的统一接口(CrudRepository,PagingAndSortingRepository)以及对持久化存储的实现。

Spring Data 包含多个子项目:

  • Commons - 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化
  • Hadoop - 基于 Spring 的 Hadoop 作业配置和一个 POJO 编程模型的 MapReduce 作业
  • Key-Value - 集成了 Redis 和 Riak ,提供多个常用场景下的简单封装
  • Document - 集成文档数据库:CouchDB 和 MongoDB 并提供基本的配置映射和资料库支持
  • Graph - 集成 Neo4j 提供强大的基于 POJO 的编程模型
  • Graph Roo AddOn - Roo support for Neo4j
  • JDBC Extensions - 支持 Oracle RAD、高级队列和高级数据类型
  • JPA - 简化创建 JPA 数据访问层和跨存储的持久层功能
  • Mapping - 基于 Grails 的提供对象映射框架,支持不同的数据库
  • Examples - 示例程序、文档和图数据库
  • Guidance - 高级文档

现在的spring-data-mongodb最新版本是2.0.6.RELEASE,大家可以从maven仓库查询最新版本以及其引用。

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>2.0.6.RELEASE</version>
</dependency>

使用spring-data-mongodb,我们可以注入mongoTemplate对象来操作MongoDB,由于没有系统的spring-data-mongodb的介绍,这里就不多说了。后面的内容会有如何使用mongoTemplate来操作数据库的。

至于在Spring项目中怎么整合mongo,可以参考这篇博文
而SpringBoot项目则非常容易,在配置文件中配置一下:spring.data.mongodb.uri等属性即可。

猜你喜欢

转载自blog.csdn.net/qq_33206732/article/details/79984235