MongoDB for Java
开发环境
操作系统: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的更多相关文章
- [MongoDB]MongoDB与JAVA结合使用CRUD
汇总: 1. [MongoDB]安装MongoDB2. [MongoDB]Mongo基本使用:3. [MongoDB]MongoDB的优缺点及与关系型数据库的比较4. [MongoDB]MongoDB ...
- 【MongoDB for Java】Java操作MongoDB
上一篇文章: http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过 ...
- 基于mongodb的java之增删改查(CRUD)
1,下载驱动https://github.com/mongodb/mongo-java-driver/downloads,导入工程java中 2,建立测试代码 import java.net.Unkn ...
- [转]MongoDB for Java】Java操作MongoDB
原文地址: MongoDB for Java]Java操作MongoDB 开发环境: System:Windows IDE:eclipse.MyEclipse 8 Database:mongoDB 开 ...
- mongodb在java驱动包下的操作(转)
推荐几章很有用的文章 java操作参考文档 http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html http://blog.csdn. ...
- mongodb的java客户端的设计思想
链接见http://api.mongodb.org/java/current/?_ga=1.111551751.200271495.1409034486 整体结构分为
- MongoDB资料--Java驱动, Hadoop驱动, Spark使用
MongoDB数据库备份: mongodump -h 192.168.1.160 -d MapLoc -o /usr/local/myjar/mongo/MapLoc/数据库还原:mongoresto ...
- MongoDB之Java测试代码(DAO层)
MongoInit.java是数据库初始化及连接类 MongoUtils.java是对mongodb的各种操作方法 MongoInit.java package com.wlwcloud.datate ...
- mongodb与java整合
mongodb与java整合需要用到mongodb驱动,如果是maven环境,则添加如下倚赖: <dependency> <groupId>org.mongodb</gr ...
- MongoDB的Java驱动使用整理 (转)
MongoDB Java Driver 简单操作 一.Java驱动一致性 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,Mongo有个内置的连接池(池大小默认为 ...
随机推荐
- LeetCode 795. Number of Subarrays with Bounded Maximum
问题链接 LeetCode 795 题目解析 给定一个数组A,左右范围L.R.求子数组的数量,要求:子数组最大值在L.R之间. 解题思路 子数组必须连续,利用最大值R对数组进行分段,设定变量 left ...
- node-redis模块需要注意的事项
node之中连接redis使用的redis模块,虽然好用,但是有些地方还是需要注意. npm install redis redis client 行为:1.客户端执行过程中断网的情况 由于原本连接正 ...
- 9. Javascript学习笔记——表单处理
9. 表单处理 9.1 表单的基础知识 ///表单用 <form> 元素表示,对应的是 HTMLFormElement 类型,继承自 HTMLElement. //属性:action.me ...
- create-react-app安装出错问题解决
在用create-react-app的时候 报错 错误如下图: 在SF上查到说是或许是因为国内npm拉去资源,拉去不到的问题,可以试着从解决创建create-react-app慢的方法着手: 解决方法 ...
- jedis 连接redis
一, 单机版连接 @Test public void testJedis() { //1. 创建jedis 对象 Jedis jedis = new Jedis("192.168.88.1 ...
- 基于MVC4+EF5.0+Ajax+Json+CSS3的简单注册页面(get&post)
使用mvc4可以很快速的创建页面,但封装的过多,难免会有些性能上的问题.所以基于此,通过使用简单的手写html,加ajax,json来创建一个注册页面,会比较干净,简洁. 本项目的环境是MVC4+EF ...
- DesUtils工具类
public final class DesUtils { private static final String DES = "DES"; private static fina ...
- vue记事1
1.组件引入css. 例:test.vue引入swiper.min.css | -- src | | -- components | | -- test | | -- test.vue | | - ...
- 使用go实现的lisp
去年10月份的时候,就有这个打算了. 也是在上个月左右,抽空弄出来了个go语言实现的lisp. 当然,不能和common lisp比,函数的数量是远远不如的,也不能自己定义类型/类,同时宏系统也非常简 ...
- free 和 delete 把指针怎么了
使用free或delete之后,只是把指针所指的内容给释放掉,但是指针并没有被干掉,还是指向原来位置(并不是执行NULL),此时指针指向的内容为垃圾,被称为“野指针”. 举例说明几个重要容易迷糊的特征 ...