开发环境

  • 操作系统:Windows7

  • IDE: MyEclipse

  • Database: MongoDB

开发依赖库

  • bson-3.0.1.jar

  • mongodb-driver-3.0.1.jar

  • mongodb-driver-core-3.0.1.jar

  • junit-4.12.jar

  • hamcrest-core-1.3.jar

PS:前三个必须引入(版本可不同),后两个为 junit 测试所用

一、准备环境

1、下载mongoDB对Java支持的驱动包

下载地址:mongodb 也可以使用Maven管理,Maven 代码片段如下:

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>bson</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

2、建立Java Project工程,导入驱动包,目录结构如下

二、Java操作 MongoDB

1、建立连接

连接数据库,需要指定数据库名,如果数据库不存在,MongoDB会自动创建它。

使用 MongoClient 来连接 MongoDB,代码片段如下:

// connect to mongodb server
MongoClient mongoClient = new MongoClient("localhost", 27017);
// connect database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mydb");

2、创建集合

要创建集合,使用 com.mongodb.client.MongoDatabase 类的 createCollection() 方法。

mongoDatabase.createCollection("person");

3、获取一个集合列表

要获取数据库中的所有集合,使用 com.mongodb.client.MongoDatabase 类的 listCollectionNames() 方法。

MongoIterable<String> result = mongoDatabase.listCollectionNames();

Iterator ite = result.iterator();
while (ite.hasNext()) {
    System.out.println("集合名字:" + ite.next());
}

4、获取/选择一个集合

要从数据库中获得/选择一个集合,使用 com.mongodb.client.MongoDatabase 类的 getCollection() 方法。

代码片段获取/选择一个集合

MongoCollection<Document> collection = mongoDatabase.getCollection("person");

5、插入文档

为了将文档插入MongoDB中,使用 com.mongodb.client.MongoCollection 类的 insertOne() 方法。

代码片段插入一个文件

MongoCollection<Document> collection = mongoDatabase.getCollection("person");
Document document = new Document("title", "MongoDB")
        .append("description", "database")
        .append("by","itmyhome");
collection.insertOne(document);

6、检索所有文件

要检索一个集合中的所有文件,使用 com.mongodb.client.MongoCollection 类的 find() 方法。

MongoCollection<Document> collection = mongoDatabase.getCollection("person");

FindIterable<Document> document = collection.find();
Iterator ite = document.iterator();

while (ite.hasNext()) {
    System.out.println(ite.next());
}

7、更新文件

从集合中更新文件,使用 com.mongodb.client.MongoCollection 类的 updateMany() 和 updateOne() 方法。

下面代码片段是将name为zhangsan的mobile信息修改为11011

MongoCollection<Document> collection = mongoDatabase.getCollection("person");
collection.updateOne(Filters.eq("name", "zhangsan"), new Document("$set", new Document("mobile", "11011")));

8、删除文件

从集合中删除文件,使用 com.mongodb.client.MongoCollection 类的 deleteMany() 和 deleteOne() 方法。

下面代码片段是删除title为MongoDB的所有文件

MongoCollection<Document> collection = mongoDatabase.getCollection("person");
collection.deleteMany(Filters.all("title", "MongoDB"));

完整代码

import java.util.Iterator;
import org.bson.Document;
import org.junit.Test;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;

/**
 * http://itmyhome.com
 * 作者: itmyhome
 */
public class CopyOfDBUtil {

    // 连接到 mongodb 服务
    MongoClient mongoClient = null;
    // 连接到数据库
    MongoDatabase mongoDatabase = null;

    /**
     * 构造方法实例化
     */
    public CopyOfDBUtil() {
        mongoClient = new MongoClient("localhost", 27017);
        mongoDatabase = mongoClient.getDatabase("mydb");
        System.out.println("Connect to database successfully: " + mongoDatabase);

    }

    /**
     * 创建集合
     */
    @Test
    public void createCollection(String collectionName) {
        mongoDatabase.createCollection(collectionName);
        System.out.println("集合: " + collectionName + " 创建成功");
    }

    /**
     * 获取所有集合
     */
    @Test
    public void getCollection() {
        MongoIterable<String> result = mongoDatabase.listCollectionNames();

        Iterator ite = result.iterator();
        while (ite.hasNext()) {
            System.out.println("集合名字:" + ite.next());
        }
    }

    /**
     * 删除集合
     */
    @Test
    public void dropCollection(String collectionName) {
        mongoDatabase.getCollection(collectionName).drop();
        System.out.println("集合:" + collectionName + " 删除成功");
    }

    /**
     * 插入文档
     */
    @Test
    public void insert() {

        // 获取所插入集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("person");
        Document document = new Document("title", "MongoDB")
                .append("description", "database")
                .append("by","itmyhome");
        collection.insertOne(document);
    }

    /**
     * 检索所有文件
     */
    @Test
    public void queryAll() {
        MongoCollection<Document> collection = mongoDatabase.getCollection("person");

        FindIterable<Document> document = collection.find();
        Iterator ite = document.iterator();

        while (ite.hasNext()) {
            System.out.println(ite.next());
        }
    }

    /**
     * 更新文件
     */
    @Test
    public void update(){
        MongoCollection<Document> collection = mongoDatabase.getCollection("person");
        collection.updateOne(Filters.eq("name", "zhangsan"),
            new Document("$set", new Document("mobile", "11011")));
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteAllDocument() {
        MongoCollection<Document> collection = mongoDatabase.getCollection("person");
        collection.deleteMany(Filters.all("title", "MongoDB"));
        System.out.println("删除成功");
    }

    /**
     * 条件查询
     */
    @Test
    public void find() {
        MongoCollection<Document> collection = mongoDatabase.getCollection("person");
        //查询likes为100的数据
        FindIterable<Document> document = collection.find(Filters.lt("likes",100));

        Iterator ite = document.iterator();
        while (ite.hasNext()) {
            System.out.println(ite.next());
        }
    }
}

作者:itmyhome

MongoDB for Java的更多相关文章

  1. [MongoDB]MongoDB与JAVA结合使用CRUD

    汇总: 1. [MongoDB]安装MongoDB2. [MongoDB]Mongo基本使用:3. [MongoDB]MongoDB的优缺点及与关系型数据库的比较4. [MongoDB]MongoDB ...

  2. 【MongoDB for Java】Java操作MongoDB

    上一篇文章: http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过 ...

  3. 基于mongodb的java之增删改查(CRUD)

    1,下载驱动https://github.com/mongodb/mongo-java-driver/downloads,导入工程java中 2,建立测试代码 import java.net.Unkn ...

  4. [转]MongoDB for Java】Java操作MongoDB

    原文地址: MongoDB for Java]Java操作MongoDB 开发环境: System:Windows IDE:eclipse.MyEclipse 8 Database:mongoDB 开 ...

  5. mongodb在java驱动包下的操作(转)

    推荐几章很有用的文章 java操作参考文档 http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html http://blog.csdn. ...

  6. mongodb的java客户端的设计思想

    链接见http://api.mongodb.org/java/current/?_ga=1.111551751.200271495.1409034486 整体结构分为

  7. MongoDB资料--Java驱动, Hadoop驱动, Spark使用

    MongoDB数据库备份: mongodump -h 192.168.1.160 -d MapLoc -o /usr/local/myjar/mongo/MapLoc/数据库还原:mongoresto ...

  8. MongoDB之Java测试代码(DAO层)

    MongoInit.java是数据库初始化及连接类 MongoUtils.java是对mongodb的各种操作方法 MongoInit.java package com.wlwcloud.datate ...

  9. mongodb与java整合

    mongodb与java整合需要用到mongodb驱动,如果是maven环境,则添加如下倚赖: <dependency> <groupId>org.mongodb</gr ...

  10. MongoDB的Java驱动使用整理 (转)

    MongoDB Java Driver 简单操作 一.Java驱动一致性 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,Mongo有个内置的连接池(池大小默认为 ...

随机推荐

  1. canvas+js+面向对象的圆形封装

    效果: Circle.js /* 1. 封装属性: x, y r, fillStyle strokeStyle opacity 2.render */ function Circle(option) ...

  2. css元素垂直居中的8中方法

    1. 通过vertical-align:middle实现CSS垂直居中 通过vertical-align:middle实现CSS垂直居中是最常使用的方法,但是有一点需要格外注意,vertical生效的 ...

  3. [温故]图解java多线程设计模式(一)

    去年看完的<图解java多线程设计模式>,可惜当时没做笔记,导致后来忘了许多东西,打算再温习下这本书,顺便在这里记录一下~  1.顺序执行.并行.并发 顺序执行:多个操作按照顺序依次执行. ...

  4. PTA 这是二叉搜索树吗?

    https://pintia.cn/problem-sets/994805046380707840/problems/994805070971912192 #include<iostream&g ...

  5. Python and Bluetooth

    环境 Windows7-64bit + Python2.7.15-64bit + Pybluez 安装pybluez时会报错,处理方法~ 1.安装VCForPython27.msi,这是为了提供vis ...

  6. C#通过反射执行C#dll所有函数

    C# 反射(Reflection) 反射指程序可以访问.检测和修改它本身状态或行为的一种能力. 程序集包含模块,而模块包含类型,类型又包含成员.反射则提供了封装程序集.模块和类型的对象. 您可以使用反 ...

  7. Visual Studio 跨平台開發實戰(3) - Xamarin iOS 多頁面應用程式開發 (转帖)

    前言 在前一篇教學中, 我們學會如何使用Visual Studio 搭配Xcode 進行iOS基本控制項的操作. 但都是屬於單一畫面的應用程式. 這次我們要來練習如何透過Navigation Cont ...

  8. Spring Boot Starters是什么?

    版权声明:该文转自: http://www.nosuchfield.com/2017/10/15/Spring-Boot-Starters/.版权归原创作者,在此对原作者的付出表示感谢! starte ...

  9. Nginx PHP fpm forbidden 原因

    可能是标红目录层级不一致 location / { root /var/www/html/public; index index.php; } location ~ \.php$ { root /va ...

  10. call()和apply()方法(切换上下文)

    call方法: 语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]]) 定义:调用一个对象的一个方法,以另一个对象替换当前对象. apply方法: 语法:apply ...