新建maven项目,添加依赖:

 <dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

测试代码:

 package com.skyer.test;

 import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import org.bson.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.QueryOperators;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult; public class TestMongo { // 声明相关变量
MongoClientURI connectionString = null;
MongoClient mongoClient = null;
MongoDatabase database = null;
MongoCollection<Document> collection = null; /**
* 获取相关对象
*/
@Before
public void getConnection() {
connectionString = new MongoClientURI("mongodb://192.168.88.128:27017"); // 服务器连接地址
mongoClient = new MongoClient(connectionString); // 获取客户端对象
database = mongoClient.getDatabase("skyer"); // 获取数据库
collection = database.getCollection("test"); // 获取连接
} /**
* 添加一个
*/
@Test
public void insert() {
Document doc = new Document("name", "skyer")
.append("type", "database")
.append("count", 1)
.append("versions", Arrays.asList("v2.7", "v4.2", "v7.2"))
.append("info", new Document("x", 27).append("y", 42));
collection.insertOne(doc);
} /**
* 批量添加
*/
@Test
public void insertMany() {
List<Document> docs = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
docs.add(new Document("i", i));
}
collection.insertMany(docs);
} /**
* 查询首个
*/
@Test
public void queryFirst() {
Document doc = collection.find().first();
System.out.println(doc.toJson());
} /**
* 查询全部
*/
@Test
public void findAll() {
for (Document doc : collection.find()) {
System.out.println(doc.toJson());
}
} /**
* 查询全部
*/
@Test
public void findAll2() {
MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} /**
* 分页查询
*/
@Test
public void findByPage() {
MongoCursor<Document> cursor = collection.find().skip(0).limit(5).iterator(); // 查询前五个记录
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} /**
* 查询一个
*/
@Test
public void findOne() {
Document doc = collection.find(new Document("i", 27)).first(); // 查询i值为27的记录
System.out.println(doc.toJson());
} /**
* 条件查询
*/
@Test
public void findByCondition1() {
BasicDBObject condition = new BasicDBObject("i", new BasicDBObject(QueryOperators.GT, 95)); // 查询i大于95的记录
MongoCursor<Document> cursor = collection.find(condition).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} /**
* 条件查询
*/
@Test
public void findByCondition2() {
BasicDBObject condition = new BasicDBObject(QueryOperators.AND,
new BasicDBObject[] {
new BasicDBObject().append("i", new BasicDBObject(QueryOperators.GT, 95)),
new BasicDBObject().append("i", new BasicDBObject(QueryOperators.LTE, 97))
}); // 查询95<i<=97的记录
MongoCursor<Document> cursor = collection.find(condition).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} /**
* 条件查询:in
*/
@Test
public void testIn() {
BasicDBObject condition = new BasicDBObject("i", new BasicDBObject(QueryOperators.IN, new int[] {27, 42}));
MongoCursor<Document> cursor = collection.find(condition).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} /**
* 条件查询:not in
*/
@Test
public void testNotIn() {
BasicDBObject condition = new BasicDBObject("i", new BasicDBObject(QueryOperators.NIN, new int[] {34, 47}));
MongoCursor<Document> cursor = collection.find(condition).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} /**
* 创建普通索引
*/
@Test
public void createIndex() {
String result = collection.createIndex(new BasicDBObject("name", 1));
System.out.println(result);
} /**
* 创建文本索引
*/
@Test
public void createTextIndex() {
String result = collection.createIndex(new Document("name", "text"));
System.out.println(result);
} /**
* 获取所有索引
*/
@Test
public void getAllIndex() {
ListIndexesIterable<Document> list = collection.listIndexes();
for (Document doc : list) {
System.out.println(doc.toJson());
}
} /**
* 删除
*/
@Test
public void testDelete() {
DeleteResult result = collection.deleteOne(new BasicDBObject("i", 2));
System.out.println(result.getDeletedCount());
} /**
* 批量删除
*/
@Test
public void testDeleteMany() {
DeleteResult result = collection.deleteMany(new BasicDBObject("i", new BasicDBObject(QueryOperators.IN, new int[] {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
})));
System.out.println(result.getDeletedCount());
} /**
* 更新
*/
@Test
public void testUpdateOne() {
UpdateResult result = collection.updateOne(new BasicDBObject("i", 10), new Document("$set", new Document("i", 110)));
System.out.println(result.getMatchedCount());
} /**
* 释放资源
*/
@After
public void releaseConnection() {
mongoClient.close();
} }

MongoDB简单操作(java版)的更多相关文章

  1. .Net Core MongoDB 简单操作。

    一:MongoDB 简单操作类.这里引用了MongoDB.Driver. using MongoDB.Bson; using MongoDB.Driver; using System; using S ...

  2. MongoDB简单操作

    Hadoop核心技术厂商Cloudera将在2014/06推出hadoop Ecosystem与MongoDB的整合产品,届时MongoDB与ipmala及hbase,hive一起用; 开源linux ...

  3. MongoDB 简单操作

    MongoDB操作 之 原生ORM,根本不存在SQL语句,数据之间不存在联系 查看数据库(查看磁盘中的数据库) > show databases; 使用数据库 > use local 创建 ...

  4. Node js MongoDB简单操作

    //win7环境下node要先安装MongoDB的相关组件(非安装MongoDB数据库),在cmd命令行进入node项目目录后执行以下语句 //npm install mongodb //创建连接 v ...

  5. java版gRPC实战之二:服务发布和调用

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  6. 【云栖社区001-数据结构】如何实现一个高效的单向链表逆序输出(Java版)

    如题 动手之前,发现自己很擅长用C语言来写链表. 不过,既然自己做的是Java开发,那么还是用Java实现这个算法吧:毕竟,以后的若干年里都差不多要跟Java打交道了. 于是,先将Java版的链表自学 ...

  7. SWFUpload简单使用样例 Java版(JSP)

    SWFUpload官方的样例都是PHP的,在这里提供一个Java版的最简单的使用样例,使用JSP页面完毕全部操作. 实现上传,分为三步: 1.JavaScript设置SWFUpload部分(与官方样例 ...

  8. java 对mongodb的操作

    java 对mongodb的操作 1.1连单台mongodb Mongo mg = newMongo();//默认连本机127.0.0.1  端口为27017 Mongo mg = newMongo( ...

  9. ORACLE的安装与网页版创建表空间的简单操作以及PLsql的简单操作

    1.oracle的安装: 安装简单易学,在这里不做解释.下载看装包后耐心等待,注意安装目录不要有中文字符,尽量按照指定目录进行安装.安装完成后会占用有大约5g的内存. 如果要卸载oracle,需要用其 ...

随机推荐

  1. kbmmw 5.08 正式发布

    欢迎大家围观. Important notes (changes that may break existing code)         ============================= ...

  2. 使用双引擎,让kbmmw 的客户端访问更方便

    前面我们一直都讲了如何使用kbmmw smarthttpservice 给客户端提供REST  服务.主要都是返回给 浏览器访问的,如果我们使用delphi 开发桌面应用,如何使用这些服务呢?其实一切 ...

  3. css3用到知识点小结

    属性 默认值 属性值及其描述 animation-name 默认值:none 规定需要绑定到选择器的 keyframe 名称. keyframename 规定需要绑定到选择器的 keyframe 的名 ...

  4. 数据库导出sql

    mysqldump -u 用户名 -p 数据库名 > 导出的文件名 mysqldump -u wcnc -p smgp_apps_wcnc > wcnc.sql

  5. POJ3040--Allowance(贪心)

    http://poj.org/problem?id=3040 思路: 输入时,如果有大于c的,直接把数量加到结果中,不把他加到数组中 把钱按面值排序 想取最大面额的钱,保证取到的钱小于等于c 然后取最 ...

  6. java基础0615

    1. 1)2)   1)输出:Base  2)编译成功,但没有输出. 2. 编译成功,但没有输出. 3. 只有12行的话,不会新建文件.需要create~~ 4. public static void ...

  7. 阿里巴巴Java开发规约及插件安装

    [上海尚学堂编辑整理]10.14日,阿里巴巴在杭州云栖大会上,正式发布了由阿里巴巴 P3C 项目组,经过 近一年的持续研发,正式发布众所期待的 <阿里巴巴 Java 开发规约>的扫描插件. ...

  8. Javascript高级编程学习笔记(51)—— DOM2和DOM3(3)操作样式表

    操作样式表 在JS中样式表用一种类型来表示,以便我们在JS对其进行操作 这一类型就是CSSStyleSheet 即CSS样式表类型,包括了之前 style 对象所不包括的外部样式表以及嵌入样式表 其中 ...

  9. IDEA远程Debug

    进行远程debug是我们排查线上bug的一个最常用的工具,本篇博文就简单介绍一下如何使用IDEA来进行远程debug 1. 修改Tomcat配置文件 修改bin目录下的catalina.sh文件,在文 ...

  10. django数据库连接快速配置

    DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql',#数据库驱动 'NAME': 'login_db',#数据库名字 'US ...