MongoDB 通过 Java 代码 CRUD 文档

本文导读

环境准备

  • 本文将使用 Maven 项目开发,开发电脑 Win10 上安装的 Maven 为 3.5.2 版本:

C:\Users\Administrator.SC-201707281232>mvn -v
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T15:58:13+08:00)
Maven home: D:\apache-maven-3.5.2\bin\..
Java version: 1.8.0_101, vendor: Oracle Corporation
Java home: D:\Java\jdk1.8.0_101\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

C:\Users\Administrator.SC-201707281232>

新建项目

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

  • 如下所示项目的 pom.xml 文件
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>www.wmx.com</groupId>
    <artifactId>mongoDB2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>mongoDB2</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- mongoDB 数据库驱动依赖:mongo-java-driver-->
        <!-- https://mongodb.github.io/mongo-java-driver/-->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.8.1</version>
        </dependency>

        <!-- Junit 测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

启动 MongoDB 服务端

C:\Users\Administrator.SC-201707281232>mongod --dbpath=D:\MongoDB\Data
2018-09-17T08:42:38.852+0800 I CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2018-09-17T08:42:39.229+0800 I CONTROL  [initandlisten] MongoDB starting : pid=16768 port=27017 dbpath=D:\MongoDB\Data 64-bit host=SC-201707281232
2018-09-17T08:42:39.229+0800 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten] db version v4.0.2-rc0
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten] git version: fc1573ba18aee42f97a3bb13b67af7d837826b47
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten] allocator: tcmalloc
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten] modules: none
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten] build environment:
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten]     distarch: x86_64
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten]     target_arch: x86_64
2018-09-17T08:42:39.230+0800 I CONTROL  [initandlisten] options: { storage: { dbPath: "D:\MongoDB\Data" } }
2018-09-17T08:42:39.235+0800 I STORAGE  [initandlisten] Detected data files in D:\MongoDB\Data created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
............

文档操作

添加文档

  • com.mongodb.client.MongoCollection#insertMany(java.util.List<? extends TDocument>) 添加多个文档
  • com.mongodb.client.MongoCollection#insertOne(TDocument):添加单个文档
  • 如下所示为集合添加单个文档:
package www.wmx.com;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * Created by Administrator on 2018/9/17 0017.
 * MongoDB 文档操作测试
 */
public class MongoDocumentTest {

    /**
     * 为指定数据库下的指定集合插入单个文档,使用:com.mongodb.client.MongoCollection#insertOne(java.lang.Object)
     * 实际开发中 文档应该尽量封装成 POJO 进行传输,本文纯粹为了演示简单,所以直接写了方法里面
     *
     * @param databaseName   :数据库名称,如果不存在,则会隐式创建
     * @param collectionName :集合名称,如果不存在,则会隐式创建
     */
    public static void insertSingleDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 服务端地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /** org.bson.Document implements Map<String, Object>, Serializable, Bson
             * Document 是 MongoDB 集合中的文档 对象,构造方法如下:
             * 1、Document()
             * 2、Document(String key, Object value) ——构造方法直接赋值
             * 3、Document(Map<String, Object> map)
             * 4、文档中可以再内嵌文档
             */
            Document document = new Document("name", "zhangSan");
            /** Object put(String key, Object value) :为文档添加值
             * Document append(String key, Object value):为文档追加值,返回的仍是源文档
             */
            document.put("age", 28);
            document.append("desc", "中国").append("price", 5578.00);

            /** insertOne(TDocument var1):为集合添加单个文档
             * insertMany(List<? extends TDocument> var1) :同时添加多个文档
             * 还以其它一些重载的方法
             * insertXxx 方法执行完,MongoDB 数据库就已经有数据了
             */
            mongoCollection.insertOne(document);
            mongoClient.close();
        }
    }
    public static void main(String[] args) {
        insertSingleDocument("java", "c2");
    }
}

MongoDB 客户端命令行可以查询:

> db
java
> db.c2.find()
{ "_id" : ObjectId("5b9f4d2f218f0d49745c7c9c"), "name" : "zhangSan", "age" : 28, "desc" : "中国", "price" : 5588 }
{ "_id" : ObjectId("5b9f4d4a218f0d36d06d7ef2"), "name" : "zhangSan", "age" : 28, "desc" : "中国", "price" : 5578 }
>

  • 如下所示,同时往集合中添加多个文档:
   /**
     * 为指定数据下的指定集合插入多个文档,使用:com.mongodb.client.MongoCollection#insertMany(java.util.List)
     * 1、为了演示方便,直接将 文档数据写死在了方法中,实际应用中应该尽量封装成 POJO 进行传递
     *
     * @param databaseName   :数据库名称,如果不存在,则会隐式创建,如 java
     * @param collectionName :集合名称,如果不存在,则会隐式创建,如 c4
     */
    public static void insertManyDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 服务器地址应该在配置文件中进行配置,不能写死*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /**
             * org.bson.Document implements Map<String, Object>, Serializable, Bson
             * Document 是 MongoDB 集合中的文档 对象,构造方法如下:
             * 1、Document()
             * 2、Document(String key, Object value)
             * 3、Document(Map<String, Object> map)
             */
            List<Document> documents = new ArrayList<Document>();
            for (int i = 0; i < 5; i++) {
                Document document = new Document("name", "Lisi");
                document.put("age", i);
                document.append("desc", "USB");
                documents.add(document);
            }

            /** insertOne(TDocument var1):为集合添加单个文档
             * insertMany(List<? extends TDocument> var1) :同时添加多个文档
             * 还以其它一些重载的方法
             * insertXxx 方法执行完,MongoDB 数据库就已经有数据了,使用 命令行可以查看:
             */
            mongoCollection.insertMany(documents);

            /**关闭 MongoDB 客户端连接,释放资源*/
            mongoClient.close();
        }
    }

    public static void main(String[] args) {
        insertManyDocument("java", "c2");
    }

MongoDB 客户端命令行可以查询:

> db
java
> db.c2.find()
{ "_id" : ObjectId("5b9f4d2f218f0d49745c7c9c"), "name" : "zhangSan", "age" : 28, "desc" : "中国", "price" : 5588 }
{ "_id" : ObjectId("5b9f4d4a218f0d36d06d7ef2"), "name" : "zhangSan", "age" : 28, "desc" : "中国", "price" : 5578 }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb39"), "name" : "Lisi", "age" : 0, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3a"), "name" : "Lisi", "age" : 1, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3b"), "name" : "Lisi", "age" : 2, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3c"), "name" : "Lisi", "age" : 3, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3d"), "name" : "Lisi", "age" : 4, "desc" : "USB" }
>

更新文档

  • com.mongodb.client.MongoCollection#updateMany(org.bson.conversions.Bson, org.bson.conversions.Bson) :同时更新多个文档
  • com.mongodb.client.MongoCollection#updateOne(org.bson.conversions.Bson, org.bson.conversions.Bson):更新检索结果中的第一个文档
 /**
     * 更新指定数据库下指定集合中的特定文档
     * 使用:com.mongodb.client.MongoCollection#updateMany(org.bson.conversions.Bson, org.bson.conversions.Bson)
     * 或者 com.mongodb.client.MongoCollection#updateOne(org.bson.conversions.Bson, org.bson.conversions.Bson)
     * 为了演示简单,更新的文档直接写死在方法中了
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     */
    public static void updateDocuments(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /**Bson bson = Filters.eq("age", 2):查询 age 等于 2 的文档,然后进行更新
             * org.bson.conversions.Bson 是一个接口
             * com.mongodb.client.model.Filters 专门用于条件查询,提供了各种检索条件*/
            Bson bson = Filters.eq("age", 2);

            /** org.bson.Document 实现了 org.bson.conversions.Bson
             * 构建修改的新文档,如下所示 如果 desc 字段源文档已经存在,则修改字段值 desc 的值为 USA,如果不存在 desc 字段,则直接添加 desc 字段,其余字段不发生变化
             * 注意更新操作,必须如下所示,设置文档的 key 为 $set,value 为 更新文档
             */
            Document document = new Document();
            document.put("$set", new Document("desc", "USA"));

            /**UpdateResult updateMany(Bson var1, Bson var2):更新查询结果中的所有文档,如果数据库文件不存在,则修改无效
             *      var1:被更新的文档,条件查询
             *      var2:更新的新文档
             * UpdateResult updateOne(Bson var1, Bson var2):更新查询结果中的第一个文档
             */
            UpdateResult updateResult = mongoCollection.updateMany(bson, document);

            /** 关闭 MongoDB 客户端*/
            mongoClient.close();
        }
    }

    public static void main(String[] args) {
        updateDocuments("java","c2");
    }

MongoDB 客户端命令查询结果:

> db
java
> db.c2.find()
{ "_id" : ObjectId("5b9f4d2f218f0d49745c7c9c"), "name" : "zhangSan", "age" : 28, "desc" : "中国", "price" : 5588 }
{ "_id" : ObjectId("5b9f4d4a218f0d36d06d7ef2"), "name" : "zhangSan", "age" : 28, "desc" : "中国", "price" : 5578 }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb39"), "name" : "Lisi", "age" : 0, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3a"), "name" : "Lisi", "age" : 1, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3b"), "name" : "Lisi", "age" : 2, "desc" : "USA" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3c"), "name" : "Lisi", "age" : 3, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3d"), "name" : "Lisi", "age" : 4, "desc" : "USB" }
>

删除文档

  • com.mongodb.client.MongoCollection#deleteOne(org.bson.conversions.Bson):删除检索结果中的第一条文档
  • com.mongodb.client.MongoCollection#deleteMany(org.bson.conversions.Bson):删除符合条件的所有文档
 /**
     * 删除指定数据库下指定集合中的文档,使用:
     * com.mongodb.client.MongoCollection#deleteOne(org.bson.conversions.Bson)
     * com.mongodb.client.MongoCollection#deleteMany(org.bson.conversions.Bson)
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @param isAllDel       :是否将匹配的文档全部删除,默认为 false,只删除第一个
     */
    public static void delDocument(String databaseName, String collectionName, Boolean isAllDel) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /**Bson bson = Filters.eq("age", 4) :删除 age 等于 4 的文档
             * Filters.eq("name", "Spring") : 删除 name 等于 Spring 的文档
             */
            /*Bson bson = Filters.eq("name", "Spring");*/
            Bson bson = Filters.eq("age", 28);

            /**deleteOne(Bson var1):删除结果中的第一个文档
             * 即如果 bson 对应多个文档,则只删除第一个
             * deleteMany(Bson var1):将匹配的文档全部删除
             */
            if (isAllDel == null || !isAllDel) {
                mongoCollection.deleteOne(bson);
            } else {
                mongoCollection.deleteMany(bson);
            }
            mongoClient.close();
        }
    }

    public static void main(String[] args) {
        delDocument("java","c2",true);
    }

MongoDB 客户端命令行查询结果,原来的值已经没有了:

> db
java
> db.c2.find()
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3a"), "name" : "Lisi", "age" : 1, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3b"), "name" : "Lisi", "age" : 2, "desc" : "USA" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3c"), "name" : "Lisi", "age" : 3, "desc" : "USB" }
{ "_id" : ObjectId("5b9f4e28218f0d439830bb3d"), "name" : "Lisi", "age" : 4, "desc" : "USB" }
>

替换文档

/**
     * 替换文档————使用一个新文档完全替换旧文档,新旧文档的主键 _id 值一致,其余字段没有任何关系
     * 更新文档是更新文档中的字段,而替换文档是替换整个文档
     * 使用 :com.mongodb.client.MongoCollection#replaceOne(org.bson.conversions.Bson, java.lang.Object)
     * 为了演示简单,查询条件直接写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document replaceDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /**UpdateResult replaceOne(Bson filter, TDocument replacement):新文档替换旧文档
             *如果有多个文档满足条件,只替换第一个
             */
            Bson bson = Filters.eq("age", 34);
            Document newDocument = new Document("name", "replaceOne");
            newDocument.append("time", new Date().getTime());
            mongoCollection.replaceOne(bson, newDocument);

            mongoClient.close();
        }
        return null;
    }
    public static void main(String[] args) {
        replaceDocument("java", "c1");
    }

替换后,使用 MongoDB 客户端命令行查看:替换前

> db.c1.find()

{ "_id" : ObjectId("5b9f40351ea234088a722a3c"), "name" : "liSi", "age" : 34 }
{ "_id" : ObjectId("5b9f5f8a1ea234088a722a3d"), "name" : "liSi", "age" : 34 }
{ "_id" : ObjectId("5b9f5f901ea234088a722a3e"), "name" : "liSi", "age" : 35 }

替换后:
> db.c1.find()
{ "_id" : ObjectId("5b9f40351ea234088a722a3c"), "name" : "replaceOne", "time" : NumberLong("1537173505172") }

{ "_id" : ObjectId("5b9f5f8a1ea234088a722a3d"), "name" : "liSi", "age" : 34 }
{ "_id" : ObjectId("5b9f5f901ea234088a722a3e"), "name" : "liSi", "age" : 35 }

查询文档

  • com.mongodb.client.MongoCollection#find():查询集合中的所有文档
 /**
     * 获取指定数据库下指定集合中的所有文档
     * 使用:com.mongodb.client.MongoCollection#find()
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> findAllDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档*/
            FindIterable<Document> documentFindIterable = mongoCollection.find();

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                documentList.add(loopDocument);
            }
            /**关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
        }
        return documentList;
    }

    public static void main(String[] args) {
        List<Document> documents = findAllDocuments("java", "c2");
        for (Document document : documents) {
            System.out.println("loopDocument>>>" + document.toJson());
        }
    }

控制台输出:

集合中文档总数为:4
firstDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3a" }, "name" : "Lisi", "age" : 1, "desc" : "USB" }
九月 17, 2018 3:17:17 下午 com.mongodb.diagnostics.logging.JULLogger log
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3a" }, "name" : "Lisi", "age" : 1, "desc" : "USB" }
信息: Closed connection [connectionId{localValue:2, serverValue:64}] to 127.0.0.1:27017 because the pool has been closed.
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3b" }, "name" : "Lisi", "age" : 2, "desc" : "USA" }
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3c" }, "name" : "Lisi", "age" : 3, "desc" : "USB" }
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3d" }, "name" : "Lisi", "age" : 4, "desc" : "USB" }

Process finished with exit code 0

  • com.mongodb.client.MongoCollection#find(org.bson.conversions.Bson):条件查询,条件查询是用的最多的,其它的修改,替换,删除都要依靠。
  • find 方法中的参数 org.bson.conversions.Bson 是一个接口,可以使用 com.mongodb.client.model.Filters 进行创建,所有的条件都可以通过 Filters 进行创建,如下所示为类中的静态方法:

Bson eq(final String fieldName, @Nullable final TItem value):查询 fieldName 的值等于 value 的文档

Bson lt(final String fieldName, final TItem value):查询 fieldName 的值小于 value 的文档

Bson lte(final String fieldName, final TItem value):查询 fieldName 的值小于等于 value 的文档

Bson gt(final String fieldName, final TItem value):查询 fieldName 的值大于 value 的文档

Bson gte(final String fieldName, final TItem value):查询 fieldName 的值大等于 value 的文档

Bson exists(final String fieldName):查询含有 fieldName 字段的文档

Bson exists(final String fieldName, final boolean exists):当 exists 为 true 时,则表示 查询含有 fieldName字段的文档;当 exists 为 false 时,表示 查询不含有 fieldName 字段的文档

Bson in(final String fieldName, final TItem... values):查询 fieldName 的值在 values 数组中的文档

Bson nin(final String fieldName, final TItem... values):查询 fieldName 的值不在 values 数组中的文档

Bson and(final Bson... filters):组合查询,逻辑与

Bson or(final Iterable<Bson> filters):组合查询,逻辑或

Bson not(final Bson filter):组合查询,逻辑非


    /**
     * 条件查询————使用 com.mongodb.client.model.Filters
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> searchDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档
             * FindIterable<TDocument> find(Bson var1):条件查询
             * Filters.eq("age", 25):查询 age 等于 25 的文档
             * Filters.lt("age",25):查询 age 小于 25 的文档
             * Filters.lte("age",25):查询 age 小于且等于 25 的文档
             * Filters.gt("age", 25):查询 age 大于 25 的文档
             * Filters.gte("age", 25):查询 age 大于且等于 25 的文档
             * */
            Bson bson = Filters.eq("age", 25);

            /** Bson bson = Filters.exists("desc"):查询含有 desc 字段的所有文档
             * Bson bson = Filters.exists("desc", false):查询不含有 desc 字段的所有文档
             */
            Bson bson1_1 = Filters.exists("desc");
            Bson bson1_2 = Filters.exists("desc", false);

            /** Bson bson = Filters.in("age", 25,28) :查询 age 等于 25 或者 age 等于28的所有文档
             * Bson bson2 = Filters.eq("name","KOKO"):查询 name 等于 KOKO 的所有文档
             */
            Bson bson2_1 = Filters.in("age", 25, 28);
            /**Bson bson = Filters.nin("age", 25,28):查询age 不等于 25 且不等于 28的文档*/
            Bson bson2_2 = Filters.nin("age", 25, 28);


            /** and(Bson... filters):组合查询,逻辑与*/
            Bson bson3 = Filters.and(bson1_1, bson2_1);

            /** or(Bson... filters):组合查询,逻辑或
             */
            Bson bson4_1 = Filters.eq("address", "湖南");
            Bson bson4_2 = Filters.or(bson3, bson4_1);

            /**组合查询,逻辑非*/
            Bson bson5 = Filters.not(bson1_1);

            FindIterable<Document> documentFindIterable = mongoCollection.find(bson1_1);

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                System.out.println("loopDocument>>>" + loopDocument.toJson());
                documentList.add(loopDocument);
            }
            /** 关闭 MongoDB 客户端*/
            mongoClient.close();
        }
        return documentList;
    }

    public static void main(String[] args) {
        searchDocuments("java", "c2");
    }

控制台输出:

集合中文档总数为:4
firstDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3a" }, "name" : "Lisi", "age" : 1, "desc" : "USB" }
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3a" }, "name" : "Lisi", "age" : 1, "desc" : "USB" }
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3b" }, "name" : "Lisi", "age" : 2, "desc" : "USA" }
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3c" }, "name" : "Lisi", "age" : 3, "desc" : "USB" }
loopDocument>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3d" }, "name" : "Lisi", "age" : 4, "desc" : "USB" }

  • com.mongodb.client.FindIterable#sort:对结果进行排序输出,这是很常见的操作,比如按着日期排序,年龄排序,姓名排序等
  • 使用 FindIterable 迭代器的 FindIterable<TResult> sort(@Nullable Bson sort) 方法,而其中的 Bson 通过 com.mongodb.client.model.Sorts 来创建,类中提供了静态方法,可以直接调用:
  • Bson ascending(final String... fieldNames):以 fieldNames 字段进行从小到大的升序排列
  • Bson descending(final String... fieldNames):以 fieldNames 字段进行从大到小的降序排列
  • Bson orderBy(final Bson... sorts):组合排序,先根据第一个 bson 排序,当第一个 bson 排序字段的值有相同时,再根据第二个 bson 进行排序,依此类推。
 /**
     * 对查询的结果进行排序——————结合 com.mongodb.client.model.Sorts
     * Bson bson1 = Sorts.ascending("age"):根据 age 由小到大排序输出
     * Bson bson2 = Sorts.descending("name"):根据 age 由大到小排序输出
     * Bson orderBy(Bson... sorts),如 orderBy(bson1,bson2):
     * 组合排序,先根据 bson1 排序,当bson1排序字段有相同时,再根据 bson2 排序,依此类推
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> getDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档
             * */
            FindIterable<Document> documentFindIterable = mongoCollection.find();

            /**descending(String... fieldNames)
             *      Bson bson1 = Sorts.ascending("age"):根据 age 由小到大排序输出
             *      Bson bson2 = Sorts.descending("name"):根据 age 由大到小排序输出
             */
            Bson bson1 = Sorts.ascending("age");
            Bson bson2 = Sorts.descending("name");

            /** Bson orderBy(Bson... sorts)
             * 组合排序,先根据 bson1 排序,当bson1排序字段有相同时,再根据 bson2 排序,依次类推
             */
            Bson bson = Sorts.orderBy(bson1, bson2);
            documentFindIterable.sort(bson);

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                System.out.println("loopDocument>>>" + loopDocument.toJson());
                documentList.add(loopDocument);
            }

            /** 关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
        }
        return documentList;
    }

    public static void main(String[] args) {
        getDocuments("java", "c1");
    }

控制台输出:

集合中文档总数为:10
firstDocument>>>{ "_id" : { "$oid" : "5b9f40281ea234088a722a39" }, "name" : "zhangSan", "age" : 32.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f40281ea234088a722a39" }, "name" : "zhangSan", "age" : 32.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f40311ea234088a722a3a" }, "name" : "liSi", "age" : 32.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f40221ea234088a722a37" }, "name" : "zhangSan", "age" : 33.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f40271ea234088a722a38" }, "name" : "zhangSan", "age" : 33.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f40331ea234088a722a3b" }, "name" : "liSi", "age" : 33.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f40351ea234088a722a3c" }, "name" : "liSi", "age" : 34.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f5f8a1ea234088a722a3d" }, "name" : "liSi", "age" : 34.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f5f901ea234088a722a3e" }, "name" : "liSi", "age" : 35.0 }
loopDocument>>>{ "_id" : { "$oid" : "5b9f5f921ea234088a722a3f" }, "name" : "liSi", "age" : 36.0 }

  • com.mongodb.client.FindIterable#projection:字段过滤查询,有时候并不需要整个文档的所有字段,而只是取其中部分字段时,这时可以过滤。
  • 使用 FindIterable 的 FindIterable<TResult> projection(@Nullable Bson projection) 方法,方法中的参数需要由 com.mongodb.client.model.Projections 类提供,其中的静态方法如下:

Bson excludeId():结果文档将不会再有 _id 主键字段

Bson exclude(final String... fieldNames):排除哪些字段不再显示

Bson include(final String... fieldNames):指定哪些字段进行显示

Bson fields(final Bson... projections):组合过滤,相当于逻辑与

 /**
     * 对查询的结果进行字段过滤,即设置哪些字段返回输出——————结合 com.mongodb.client.model.Projections
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> loadDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档
             * */
            FindIterable<Document> documentFindIterable = mongoCollection.find();

            /** Bson bson = Projections.excludeId():结果中文档将不会再有 _id 主键字段
             * Bson exclude(String... fieldNames) :排除哪些字段不再显示
             *      如 Projections.exclude("name", "age"):表示结果中文档将不会再有 name、age 字段
             * Bson include(String... fieldNames):包含哪些字段进行显示
             *      如 Projections.include("desc","name"):表示结果中文档只包含 desc、name 以及主键 _id 字段
             */
            Bson bson1 = Projections.excludeId();
            Bson bson2 = Projections.exclude("age");
            Bson bson3 = Projections.include("desc", "name");

            /**Bson fields(Bson... projections):组合过滤,相当于 逻辑与*/
            Bson bson = Projections.fields(bson1, bson2);
            documentFindIterable.projection(bson);

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                System.out.println("loopDocument>>>" + loopDocument.toJson());
                documentList.add(loopDocument);
            }
            /** 关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
        }
        return documentList;
    }

    public static void main(String[] args) {
        loadDocuments("java", "c1");
    }

控制台输出:

集合中文档总数为:5
firstDocument>>>{ "name" : "zhangSan" }
loopDocument>>>{ "name" : "zhangSan" }
loopDocument>>>{ "name" : "zhangSan" }
loopDocument>>>{ "name" : "zhangSan" }
loopDocument>>>{ "name" : "liSi" }
loopDocument>>>{ "name" : "liSi" }

查询并删除

  • com.mongodb.client.MongoCollection#findOneAndDelete(org.bson.conversions.Bson):查询并删除文档,取值之后,原来的值就会被删除,值只能取一次,可用于做消息队列等场景。
  • 如果有多条值满足条件,只取第一条
 /**
     * 查询并删除----------即取值之后,原来的值就会被删除,值只能取一次,可用于做消息队列等场景
     * 使用 :com.mongodb.client.MongoCollection#findOneAndDelete(org.bson.conversions.Bson)
     * 为了演示简单,查询条件直接写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document findAndDelDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** findOneAndDelete(Bson var1):条件查询并删除,查询符合条件的第一条数据,返回之后,删除源数据
             *  即 值只取一次,取完一次就没有了,适合做消息队列,没有查询到值时,返回 null
             *  如下所示:查询 age 等于 28的文档中的第一条,查询之后集合中便没有它了
             */
            Bson bson = Filters.eq("age", 33);
            Document document = mongoCollection.findOneAndDelete(bson);
            if (document != null) {
                System.out.println("document>>>" + document.toJson());
            }
            mongoClient.close();
            return document;
        }
        return null;
    }

    public static void main(String[] args) {
        findAndDelDocument("java", "c1");
    }

查询并替换

/**
     * 查询并替换----------即取值之后,用一个新文档来替换旧文档,整个旧文档不复存在,由新文档取代,两者主键 _id 字段值相同
     * 如果有个文档符合条件,则只操作第一个文档
     * 使用:com.mongodb.client.MongoCollection#findOneAndReplace(org.bson.conversions.Bson, java.lang.Object)
     * 为了演示简单,查询条件 与 替换文档 直接写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document findAndReplaceDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** findOneAndReplace(Bson var1, TDocument var2):条件查询并更新
             *      查询符合条件的第一条数据,返回之后,用新文档替换旧文档,没有查询到值时,返回 null
             *  如下所示查询 age 等于 6的第一条文档,然后用一个新文档替换源文档,主键 _id 不会变化
             */
            Bson bson = Filters.eq("age", 33);
            Document newDocument = new Document("type", "success");
            newDocument.append("time", new Date().getTime());
            Document document = mongoCollection.findOneAndReplace(bson, newDocument);

            if (document != null) {
                System.out.println("document>>>" + document.toJson());
            }
            /**关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
            return document;
        }
        return null;
    }

    public static void main(String[] args) {
        findAndReplaceDocument("java", "c1");
    }

forEach 文档遍历

  • 对于集合中的文档遍历方式之一是如下所示,先获取迭代器,然后根据迭代器获取游标,最后遍历游标进行取值

FindIterable<Document> documentFindIterable = mongoCollection.find();
MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();

  • 同时 MongoCollection 直接提供了遍历的 forEach 方法,如下所示重载的两个方法,效果完全一致:

forEach(Block<? super TResult> block)
forEach(Consumer<? super T> action)

/**
     * 遍历文档迭代器,两个重载的 forEach 方法
     * 1)forEach(Block<? super TResult> var1)
     * 2)forEach(Consumer<? super T> action)
     * <p/>
     * 为了演示简单,查询条件写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document forEachDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            MongoIterable<Document> mongoIterable = mongoCollection.find();

            /** 除了 MongoCursor<Document> mongoCursor = mongoIterable.iterator() 使用游标进行遍历之外
             *  因为 MongoDB 可以使用 js 引擎进行解析,所以还可以使用 forEach(Block<? super TResult> var1) 方法
             *  类似 JQuery 的 each 遍历
             */
            mongoIterable.forEach(new Block<Document>() {
                @Override
                public void apply(Document document) {
                    System.out.println("block document>>>" + document.toJson());
                }
            });

            /** forEach 还有一个重载的方法 forEach(Consumer<? super T> action)
             * 效果完全一致控制台输出示例:
             */
            System.out.println("=================================");
            mongoIterable.forEach(new Consumer<Document>() {
                @Override
                public void accept(Document document) {
                    System.out.println("consumer document>>>" + document.toJson());
                }
            });
            mongoClient.close();
        }
        return null;
    }

    public static void main(String[] args) {
        forEachDocument("java", "c2");
    }

控制台输出:

集合中文档总数为:4
block document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3a" }, "name" : "Lisi", "age" : 1, "desc" : "USB" }
block document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3b" }, "name" : "Lisi", "age" : 2, "desc" : "USA" }
block document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3c" }, "name" : "Lisi", "age" : 3, "desc" : "USB" }
block document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3d" }, "name" : "Lisi", "age" : 4, "desc" : "USB" }
=================================
consumer document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3a" }, "name" : "Lisi", "age" : 1, "desc" : "USB" }
consumer document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3b" }, "name" : "Lisi", "age" : 2, "desc" : "USA" }
consumer document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3c" }, "name" : "Lisi", "age" : 3, "desc" : "USB" }
consumer document>>>{ "_id" : { "$oid" : "5b9f4e28218f0d439830bb3d" }, "name" : "Lisi", "age" : 4, "desc" : "USB" }

整个文件内容

package www.wmx.com;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

/**
 * Created by Administrator on 2018/9/17 0017.
 * MongoDB 文档操作测试
 */
public class MongoDocumentTest {

    /**
     * 为指定数据库下的指定集合插入单个文档,使用:com.mongodb.client.MongoCollection#insertOne(java.lang.Object)
     * 实际开发中 文档应该尽量封装成 POJO 进行传输,本文纯粹为了演示简单,所以直接写了方法里面
     *
     * @param databaseName   :数据库名称,如果不存在,则会隐式创建
     * @param collectionName :集合名称,如果不存在,则会隐式创建
     */
    public static void insertSingleDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 服务端地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /** org.bson.Document implements Map<String, Object>, Serializable, Bson
             * Document 是 MongoDB 集合中的文档 对象,构造方法如下:
             * 1、Document()
             * 2、Document(String key, Object value) ——构造方法直接赋值
             * 3、Document(Map<String, Object> map)
             * 4、文档中可以再内嵌文档
             */
            Document document = new Document("name", "zhangSan");
            /** Object put(String key, Object value) :为文档添加值
             * Document append(String key, Object value):为文档追加值,返回的仍是源文档
             */
            document.put("age", 28);
            document.append("desc", "中国").append("price", 5578.00);

            /** insertOne(TDocument var1):为集合添加单个文档
             * insertMany(List<? extends TDocument> var1) :同时添加多个文档
             * 还以其它一些重载的方法
             * insertXxx 方法执行完,MongoDB 数据库就已经有数据了
             */
            mongoCollection.insertOne(document);
            mongoClient.close();
        }
    }

    /**
     * 为指定数据下的指定集合插入多个文档,使用:com.mongodb.client.MongoCollection#insertMany(java.util.List)
     * 1、为了演示方便,直接将 文档数据写死在了方法中,实际应用中应该尽量封装成 POJO 进行传递
     *
     * @param databaseName   :数据库名称,如果不存在,则会隐式创建,如 java
     * @param collectionName :集合名称,如果不存在,则会隐式创建,如 c4
     */
    public static void insertManyDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 服务器地址应该在配置文件中进行配置,不能写死*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /**
             * org.bson.Document implements Map<String, Object>, Serializable, Bson
             * Document 是 MongoDB 集合中的文档 对象,构造方法如下:
             * 1、Document()
             * 2、Document(String key, Object value)
             * 3、Document(Map<String, Object> map)
             */
            List<Document> documents = new ArrayList<Document>();
            for (int i = 0; i < 5; i++) {
                Document document = new Document("name", "Lisi");
                document.put("age", i);
                document.append("desc", "USB");
                documents.add(document);
            }

            /** insertOne(TDocument var1):为集合添加单个文档
             * insertMany(List<? extends TDocument> var1) :同时添加多个文档
             * 还以其它一些重载的方法
             * insertXxx 方法执行完,MongoDB 数据库就已经有数据了,使用 命令行可以查看:
             */
            mongoCollection.insertMany(documents);

            /**关闭 MongoDB 客户端连接,释放资源*/
            mongoClient.close();
        }
    }

    /**
     * 更新指定数据库下指定集合中的特定文档
     * 使用:com.mongodb.client.MongoCollection#updateMany(org.bson.conversions.Bson, org.bson.conversions.Bson)
     * 或者 com.mongodb.client.MongoCollection#updateOne(org.bson.conversions.Bson, org.bson.conversions.Bson)
     * 为了演示简单,更新的文档直接写死在方法中了
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     */
    public static void updateDocuments(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /**Bson bson = Filters.eq("age", 2):查询 age 等于 2 的文档,然后进行更新
             * org.bson.conversions.Bson 是一个接口
             * com.mongodb.client.model.Filters 专门用于条件查询,提供了各种检索条件*/
            Bson bson = Filters.eq("age", 2);

            /** org.bson.Document 实现了 org.bson.conversions.Bson
             * 构建修改的新文档,如下所示 如果 desc 字段源文档已经存在,则修改字段值 desc 的值为 USA,如果不存在 desc 字段,则直接添加 desc 字段,其余字段不发生变化
             * 注意更新操作,必须如下所示,设置文档的 key 为 $set,value 为 更新文档
             */
            Document document = new Document();
            document.put("$set", new Document("desc", "USA"));

            /**UpdateResult updateMany(Bson var1, Bson var2):更新查询结果中的所有文档,如果数据库文件不存在,则修改无效
             *      var1:被更新的文档,条件查询
             *      var2:更新的新文档
             * UpdateResult updateOne(Bson var1, Bson var2):更新查询结果中的第一个文档
             */
            UpdateResult updateResult = mongoCollection.updateMany(bson, document);

            /** 关闭 MongoDB 客户端*/
            mongoClient.close();
        }
    }

    /**
     * 删除指定数据库下指定集合中的文档,使用:
     * com.mongodb.client.MongoCollection#deleteOne(org.bson.conversions.Bson)
     * com.mongodb.client.MongoCollection#deleteMany(org.bson.conversions.Bson)
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @param isAllDel       :是否将匹配的文档全部删除,默认为 false,只删除第一个
     */
    public static void delDocument(String databaseName, String collectionName, Boolean isAllDel) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            /**Bson bson = Filters.eq("age", 4) :删除 age 等于 4 的文档
             * Filters.eq("name", "Spring") : 删除 name 等于 Spring 的文档
             */
            /*Bson bson = Filters.eq("name", "Spring");*/
            Bson bson = Filters.eq("age", 28);

            /**deleteOne(Bson var1):删除结果中的第一个文档
             * 即如果 bson 对应多个文档,则只删除第一个
             * deleteMany(Bson var1):将匹配的文档全部删除
             */
            if (isAllDel == null || !isAllDel) {
                mongoCollection.deleteOne(bson);
            } else {
                mongoCollection.deleteMany(bson);
            }
            mongoClient.close();
        }
    }

    /**
     * 获取指定数据库下指定集合中的所有文档
     * 使用:com.mongodb.client.MongoCollection#find()
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> findAllDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档*/
            FindIterable<Document> documentFindIterable = mongoCollection.find();

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                documentList.add(loopDocument);
            }
            /**关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
        }
        return documentList;
    }

    /**
     * 条件查询————使用 com.mongodb.client.model.Filters
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> searchDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档
             * FindIterable<TDocument> find(Bson var1):条件查询
             * Filters.eq("age", 25):查询 age 等于 25 的文档
             * Filters.lt("age",25):查询 age 小于 25 的文档
             * Filters.lte("age",25):查询 age 小于且等于 25 的文档
             * Filters.gt("age", 25):查询 age 大于 25 的文档
             * Filters.gte("age", 25):查询 age 大于且等于 25 的文档
             * */
            Bson bson = Filters.eq("age", 25);

            /** Bson bson = Filters.exists("desc"):查询含有 desc 字段的所有文档
             * Bson bson = Filters.exists("desc", false):查询不含有 desc 字段的所有文档
             */
            Bson bson1_1 = Filters.exists("desc");
            Bson bson1_2 = Filters.exists("desc", false);

            /** Bson bson = Filters.in("age", 25,28) :查询 age 等于 25 或者 age 等于28的所有文档
             * Bson bson2 = Filters.eq("name","KOKO"):查询 name 等于 KOKO 的所有文档
             */
            Bson bson2_1 = Filters.in("age", 25, 28);
            /**Bson bson = Filters.nin("age", 25,28):查询age 不等于 25 且不等于 28的文档*/
            Bson bson2_2 = Filters.nin("age", 25, 28);


            /** and(Bson... filters):组合查询,逻辑与*/
            Bson bson3 = Filters.and(bson1_1, bson2_1);

            /** or(Bson... filters):组合查询,逻辑或
             */
            Bson bson4_1 = Filters.eq("address", "湖南");
            Bson bson4_2 = Filters.or(bson3, bson4_1);

            /**组合查询,逻辑非*/
            Bson bson5 = Filters.not(bson1_1);

            FindIterable<Document> documentFindIterable = mongoCollection.find(bson1_1);

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                System.out.println("loopDocument>>>" + loopDocument.toJson());
                documentList.add(loopDocument);
            }
            /** 关闭 MongoDB 客户端*/
            mongoClient.close();
        }
        return documentList;
    }

    /**
     * 对查询的结果进行排序——————结合 com.mongodb.client.model.Sorts
     * Bson bson1 = Sorts.ascending("age"):根据 age 由小到大排序输出
     * Bson bson2 = Sorts.descending("name"):根据 age 由大到小排序输出
     * Bson orderBy(Bson... sorts),如 orderBy(bson1,bson2):
     * 组合排序,先根据 bson1 排序,当bson1排序字段有相同时,再根据 bson2 排序,依此类推
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> getDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档
             * */
            FindIterable<Document> documentFindIterable = mongoCollection.find();

            /**descending(String... fieldNames)
             *      Bson bson1 = Sorts.ascending("age"):根据 age 由小到大排序输出
             *      Bson bson2 = Sorts.descending("name"):根据 age 由大到小排序输出
             */
            Bson bson1 = Sorts.ascending("age");
            Bson bson2 = Sorts.descending("name");

            /** Bson orderBy(Bson... sorts)
             * 组合排序,先根据 bson1 排序,当bson1排序字段有相同时,再根据 bson2 排序,依次类推
             */
            Bson bson = Sorts.orderBy(bson1, bson2);
            documentFindIterable.sort(bson);

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                System.out.println("loopDocument>>>" + loopDocument.toJson());
                documentList.add(loopDocument);
            }

            /** 关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
        }
        return documentList;
    }

    /**
     * 对查询的结果进行字段过滤,即设置哪些字段返回输出——————结合 com.mongodb.client.model.Projections
     *
     * @param databaseName   :数据库名
     * @param collectionName :数据库下的集合名
     * @return
     */
    public static List<Document> loadDocuments(String databaseName, String collectionName) {
        List<Document> documentList = new ArrayList<Document>();
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** find():获取集合中的所有文档
             * */
            FindIterable<Document> documentFindIterable = mongoCollection.find();

            /** Bson bson = Projections.excludeId():结果中文档将不会再有 _id 主键字段
             * Bson exclude(String... fieldNames) :排除哪些字段不再显示
             *      如 Projections.exclude("name", "age"):表示结果中文档将不会再有 name、age 字段
             * Bson include(String... fieldNames):包含哪些字段进行显示
             *      如 Projections.include("desc","name"):表示结果中文档只包含 desc、name 以及主键 _id 字段
             */
            Bson bson1 = Projections.excludeId();
            Bson bson2 = Projections.exclude("age");
            Bson bson3 = Projections.include("desc", "name");

            /**Bson fields(Bson... projections):组合过滤,相当于 逻辑与*/
            Bson bson = Projections.fields(bson1, bson2);
            documentFindIterable.projection(bson);

            /**从 FindIterable<Document> 获取第一个文档,不存在時,返回null*/
            Document firstDocument = documentFindIterable.first();
            if (firstDocument != null) {
                System.out.println("firstDocument>>>" + firstDocument.toJson());
            }
            /** 获取迭代器游标,遍历每个文档,集合为空时,则大小为0,不为null*/
            MongoCursor<Document> documentMongoCursor = documentFindIterable.iterator();
            while (documentMongoCursor.hasNext()) {
                Document loopDocument = documentMongoCursor.next();
                System.out.println("loopDocument>>>" + loopDocument.toJson());
                documentList.add(loopDocument);
            }
            /** 关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
        }
        return documentList;
    }

    /**
     * 替换文档————使用一个新文档完全替换旧文档,新旧文档的主键 _id 值一致,其余字段没有任何关系
     * 更新文档是更新文档中的字段,而替换文档是替换整个文档
     * 使用 :com.mongodb.client.MongoCollection#replaceOne(org.bson.conversions.Bson, java.lang.Object)
     * 为了演示简单,查询条件直接写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document replaceDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /**UpdateResult replaceOne(Bson filter, TDocument replacement):新文档替换旧文档
             *如果有多个文档满足条件,只替换第一个
             */
            Bson bson = Filters.eq("age", 34);
            Document newDocument = new Document("name", "replaceOne");
            newDocument.append("time", new Date().getTime());
            mongoCollection.replaceOne(bson, newDocument);

            mongoClient.close();
        }
        return null;
    }

    /**
     * 查询并删除----------即取值之后,原来的值就会被删除,值只能取一次,可用于做消息队列等场景
     * 使用 :com.mongodb.client.MongoCollection#findOneAndDelete(org.bson.conversions.Bson)
     * 为了演示简单,查询条件直接写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document findAndDelDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** findOneAndDelete(Bson var1):条件查询并删除,查询符合条件的第一条数据,返回之后,删除源数据
             *  即 值只取一次,取完一次就没有了,适合做消息队列,没有查询到值时,返回 null
             *  如下所示:查询 age 等于 28的文档中的第一条,查询之后集合中便没有它了
             */
            Bson bson = Filters.eq("age", 33);
            Document document = mongoCollection.findOneAndDelete(bson);
            if (document != null) {
                System.out.println("document>>>" + document.toJson());
            }
            mongoClient.close();
            return document;
        }
        return null;
    }

    /**
     * 查询并替换----------即取值之后,用一个新文档来替换旧文档,整个旧文档不复存在,由新文档取代,两者主键 _id 字段值相同
     * 如果有个文档符合条件,则只操作第一个文档
     * 使用:com.mongodb.client.MongoCollection#findOneAndReplace(org.bson.conversions.Bson, java.lang.Object)
     * 为了演示简单,查询条件 与 替换文档 直接写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document findAndReplaceDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            /** findOneAndReplace(Bson var1, TDocument var2):条件查询并更新
             *      查询符合条件的第一条数据,返回之后,用新文档替换旧文档,没有查询到值时,返回 null
             *  如下所示查询 age 等于 6的第一条文档,然后用一个新文档替换源文档,主键 _id 不会变化
             */
            Bson bson = Filters.eq("age", 33);
            Document newDocument = new Document("type", "success");
            newDocument.append("time", new Date().getTime());
            Document document = mongoCollection.findOneAndReplace(bson, newDocument);

            if (document != null) {
                System.out.println("document>>>" + document.toJson());
            }
            /**关闭 MongoDB 客户端,释放资源*/
            mongoClient.close();
            return document;
        }
        return null;
    }

    /**
     * 遍历文档迭代器,两个重载的 forEach 方法
     * 1)forEach(Block<? super TResult> var1)
     * 2)forEach(Consumer<? super T> action)
     * <p/>
     * 为了演示简单,查询条件写死在方法中了
     *
     * @param databaseName   :数据库名称
     * @param collectionName :集合名称
     */
    public static Document forEachDocument(String databaseName, String collectionName) {
        if (databaseName != null && !"".equals(databaseName) && collectionName != null && !"".equals(collectionName)) {
            /** MongoClient(String host, int port):直接指定 MongoDB IP 与端口进行连接
             * 实际应用中 MongoDB 地址应该配置在配置文件中*/
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

            /**getDatabase(String databaseName):获取指定的数据库
             * 如果此数据库不存在,则会自动创建,此时存在内存中,服务器不会存在真实的数据库文件,show dbs 命令 看不到
             * 如果再往其中添加数据,服务器则会生成数据库文件,磁盘中会真实存在,show dbs 命令 可以看到
             * */
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

            /**获取数据库中的集合
             * 如果集合不存在,则会隐式创建,此时在内存中,MongoDB 客户端 show tables 看不到
             * 如果继续往集合插入值,则会真实写入磁盘中,show tables 会有值*/
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);

            Long documentSize = mongoCollection.countDocuments();
            System.out.println("集合中文档总数为:" + documentSize);

            MongoIterable<Document> mongoIterable = mongoCollection.find();

            /** 除了 MongoCursor<Document> mongoCursor = mongoIterable.iterator() 使用游标进行遍历之外
             *  因为 MongoDB 可以使用 js 引擎进行解析,所以还可以使用 forEach(Block<? super TResult> var1) 方法
             *  类似 JQuery 的 each 遍历
             */
            mongoIterable.forEach(new Block<Document>() {
                @Override
                public void apply(Document document) {
                    System.out.println("block document>>>" + document.toJson());
                }
            });

            /** forEach 还有一个重载的方法 forEach(Consumer<? super T> action)
             * 效果完全一致控制台输出示例:
             */
            System.out.println("=================================");
            mongoIterable.forEach(new Consumer<Document>() {
                @Override
                public void accept(Document document) {
                    System.out.println("consumer document>>>" + document.toJson());
                }
            });
            mongoClient.close();
        }
        return null;
    }

    public static void main(String[] args) {
        forEachDocument("java", "c2");
    }

}

猜你喜欢

转载自blog.csdn.net/wangmx1993328/article/details/82736353
今日推荐