MongoDB Java(七)

在 Java 程序中如果要使用 MongoDB,你需要确保已经安装了 Java 环境及 MongoDB JDBC 驱动。

mongodb-driver jar 下载地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/

操作文档:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/

或mave pom.xml

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

 

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;

/**
 * mongo-java-driver 基础操作
 */
public class StandaloneMongodbDoc {
    /*** 地址 */
    private static final String MONGODB_ADDRESS = "192.168.178.6";
    /*** 端口 */
    private static final Integer MONGODB_PORT = 27017;
    /*** 集合名称 */
    private static final String COLLECTION_NAME = "java";

    /*** 连接 */
    private static MongoClient mongoClient;
    /*** 数据库 */
    private static MongoDatabase database;
    /*** 集合 */
    private static MongoCollection<Document> collection;

    public static void main(String[] args) {
        // 建立连接
        newConnection();
        // 查询所有数据库
        listDataBaseNames();
        // 获取数据库
        getDataBase();
        // 创建集合
        createCollection();
        // 获取集合
        getCollection();
        // 插入文档
        insertDoc();
        // 检索所有文档
        findAllDoc();
        // 更新文档
        updateDoc();
        // 删除文档
        removeDoc();
        // 条件查找 (匹配)
        findByEq();
        //条件查找 [小于]
        findByLt();
        //条件查找 [小于等于]
        findByLte();
        //条件查找 [大于]
        findByGt();
        //条件查找 [大于等于]
        findByGte();
        //条件查找 [and]
        findByAnd();
        //条件查找 [or]
        findByOr();
        //排序[降序]
        sortDoc();
        

    }

    private static void newConnection() {
        System.out.println("==================== newMongoClient ====================");
        mongoClient = new MongoClient(MONGODB_ADDRESS, MONGODB_PORT);
    }

    private static void listDataBaseNames() {
        System.out.println("==================== listDatabases ====================");
        MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();
        for (String dbName : databaseNames) {
            System.out.println(dbName);
        }
    }

    private static void getDataBase() {
        System.out.println("==================== getDatabase ====================");
        database = mongoClient.getDatabase("mydb");
    }

    private static void createCollection() {
        System.out.println("==================== createCollection ====================");
        database.createCollection(COLLECTION_NAME);
    }

    private static void getCollection() {
        System.out.println("==================== getCollection ====================");
        collection = database.getCollection(COLLECTION_NAME);
    }

    private static void insertDoc() {
        System.out.println("==================== insertDoc ====================");
        // 插入一条文档
        Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
                new Document("x", 203).append("y", 102));
        collection.insertOne(doc);
        // 插入多条文档
        List<Document> documents = new ArrayList<Document>();
        Document document1 = new Document().append("title", "php").append("desc", "PHP是世界上最好的语言").append("by", "yanwu")
                .append("tage", Collections.singletonList("php")).append("likes", 100);
        documents.add(document1);

        Document document2 = new Document().append("title", "python").append("desc", "python是人工智能的未来")
                .append("by", "yanwu").append("tage", Collections.singletonList("python")).append("likes", 250);
        documents.add(document2);

        Document document3 = new Document().append("title", "mongodb").append("desc", "学习学习").append("by", "yanwu")
                .append("tage", Collections.singletonList("mongodb")).append("likes", 150);
        documents.add(document3);

        collection.insertMany(documents);

        // 计算文档数量
        System.out.println(collection.countDocuments());

    }

    private static void findAllDoc() {
        System.out.println("==================== findAllDoc ====================");
        print(collection.find());
    }

    private static void updateDoc() {
        System.out.println("==================== updateDoc ====================");
        collection.updateMany(Filters.eq("title", "java"), new Document("$set", new Document("title", "java语言")));
        // 类似于 update java set title='java语言' where title='java';
        findAllDoc();
    }

    private static void removeDoc() {
        System.out.println("==================== removeDoc ====================");
        // 删除一个文档
        collection.deleteOne(Filters.eq("title", "java"));
        findAllDoc();
        // 删除多个文档
        collection.deleteMany(Filters.eq("by", "yanwu"));
        findAllDoc();
    }

    private static void findByEq() {
        System.out.println("==================== findByEq: likes == 200 ====================");
        print(collection.find(Filters.eq("likes", 200)));
    }

    
    private static void findByLt() {
        System.out.println("==================== findByLt: likes < 200 ====================");
        print(collection.find(Filters.lt("likes", 200)));
    }

    private static void findByLte() {
        System.out.println("==================== findByLte: likes <= 200 ====================");
        print(collection.find(Filters.lte("likes", 200)));
    }

    private static void findByGt() {
        System.out.println("==================== findByGt: likes > 200 ====================");
        print(collection.find(Filters.gt("likes", 200)));
    }
    
    private static void findByGte() {
        System.out.println("==================== findByGte: likes >= 200 ====================");
        print(collection.find(Filters.gte("likes", 200)));
    }

    private static void findByAnd() {
        System.out.println("==================== findByGte: likes > 150 && likes < 250 ====================");
        print(collection.find(Filters.and(Filters.gt("likes", 150), Filters.lt("likes", 250))));
    }

    private static void findByOr() {
        System.out.println("==================== findByGte: likes < 150 || likes > 200 ====================");
        print(collection.find(Filters.or(Filters.lt("likes", 150), Filters.gt("likes", 200))));
    }
    
    private static void sortDoc(){
        System.out.println("==================== sortDoc ====================");
        //Sorts.descending 表示降序
        collection.find(Filters.exists("likes")).sort(Sorts.descending("likes")).first();
    }

    /**
     * 方式一:打印输出文档集合
     */
    private static void print(FindIterable<Document> documents) {
        for (Document document : documents) {
            System.out.println(document.toJson());
        }
    }

    /**
     * 方式二:打印输出文档集合
     */
    private static void printByCursor(FindIterable<Document> documents) {
        MongoCursor<Document> cursor = documents.iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }
    
}

 

posted @ 2019-09-29 21:50  codedot  阅读(332)  评论(0编辑  收藏  举报