本人使用maven创建的java工程,mongo-java-driver使用的是3.2.2,这个驱动2.x和3.x是有差异的

pom.xml配置加入:

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

//创建MongoDemo 项目

package org.demo.MongoDBDemo.TestMongo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;

public class MongoDemo {
public static void main(String[] args) {
// 1.连接方式一:
// 连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
// ServerAddress()两个参数分别为 服务器地址 和 端口
/*
* ServerAddress serverAddress=new ServerAddress("localhost",10086);
* List<ServerAddress> address=new ArrayList<ServerAddress>();
* address.add(serverAddress);
*
* //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
* MongoCredential credential= MongoCredential.createCredential("hello", "mldn",
* "java".toCharArray());
*
* List<MongoCredential> credentials=new ArrayList<MongoCredential>();
* credentials.add(credential); //通过连接认证获取MongoDB连接 MongoClient client=new
* MongoClient(address, credentials);
*/

// 连接方式二:通过URI的方式区连接,类似jdbc
// uri格式:mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
MongoClientURI uri = new MongoClientURI("mongodb://hello:java@localhost:10086/mldn");
MongoClient client = new MongoClient(uri);
// 获得指定集合
MongoDatabase db = client.getDatabase("mldn");

MongoCollection<Document> students = db.getCollection("students");

// 通过Document查询条件
// 查找所有name = 张三的document
Document query1 = new Document("name", "张三");

// 使用运算符“$lt”,"$gt","$lte","$gte"
// age < 25
Document query2 = new Document("age", new Document("$lt", 25));

// and连接多个条件,在后面追加append ,
// 25>age>18
Document query3 = new Document("age", new Document("$lt", 25)).append("age", new Document("$gt", 18));

// or连接多个条件
// name = 大神B || name == 大神E
Document query4 = new Document("$or", Arrays.asList(new Document("name", "大神B"), new Document("name", "大神E")));

// between...and..
Document query5 = new Document("age", new Document("$lt", 25).append("$gt", 18));

FindIterable<Document> documents = students.find(query5);
for (Document document : documents) {
System.out.println(document.toJson());
}

// 通过Filters指定查询条件(更简洁的做法)
// 相等:eq
FindIterable<Document> result1= students.find(Filters.eq("name", "孙七"));

//不等:ne、lt、lte、gt、gte
// <=23
FindIterable<Document> result2 = students.find(Filters.lte("age", 23));

//in
FindIterable<Document> result3 = students.find(Filters.in("age", Arrays.asList(23,18,27)));

//and:名字是大神B,年龄不是23
Bson and = Filters.and(Filters.eq("name", "大神B"), Filters.ne("age", 22));
FindIterable<Document> result4 = students.find(and);

//or:
FindIterable<Document> result5 = students.find(Filters.or(Filters.eq("age",23),Filters.eq("age", 18)));

for (Document document : result5) {
System.out.println(document.toJson());
}

//计算数量,count
long cnt = students.count(Filters.eq("age", 18));
System.out.println(cnt);

//sort
//按name升序
FindIterable<Document> documents1 = students.find().sort(Sorts.ascending("name"));
//按age将序
FindIterable<Document> documents2 = students.find().sort(Sorts.descending("age"));
//按name升序,name相同的按age降序
FindIterable<Document> documents3 = students.find().sort(Sorts.orderBy(Sorts.ascending("name"), Sorts.descending("age")));

//skipe & limit
//跳过前2条(0-1),返回(2-4)共3条。
FindIterable<Document> documents4 = students.find().sort(Sorts.descending("age")).skip(2).limit(3);
for (Document document : documents4) {
System.out.println("分页:"+document);
}

//distinct,去重复数据
DistinctIterable<String> documents5 = students.distinct("name", String.class);
for (String document : documents5) {
System.out.println("去重:"+document);
}

//添加document
//添加单个document
Document doc = new Document();
doc.put("name", "pikaqiu");
doc.put("age", 12);
students.insertOne(doc);
//添加多个文档
List<Document> docs = new LinkedList<Document>();
for(int i=0; i<10; i++){
Document doc1 = new Document();
doc1.put("name", "皮卡丘"+i);
doc1.put("age", 1+i);
docs.add(doc1);
}
students.insertMany(docs);

//修改document
//updateOne/updateMany:
students.updateMany(Filters.eq("age", 25), new Document("$set", new Document("age", 16).append("name","xxx25")));

//删除document
//deleteOne/deleteMany:
//删除第一个符合条件的
students.deleteOne(Filters.eq("age", 17));
//删除所有符合条件的
students.deleteMany(Filters.eq("age", 17));

}
}

参考博客:http://www.cnblogs.com/minsons/articles/7026600.html

http://www.cnblogs.com/gotodsp/p/6673357.html

MongoDB学习笔记-2(使用java连接Mongo)的更多相关文章

  1. [Spring Data MongoDB]学习笔记--注册一个Mongo实例

    1. 通过Java based bean metadata @Configuration public class AppConfig { public @Bean Mongo mongo() thr ...

  2. mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...

  3. 【转】mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    mongoDB 学习笔记纯干货(mongoose.增删改查.聚合.索引.连接.备份与恢复.监控等等) http://www.cnblogs.com/bxm0927/p/7159556.html

  4. MongoDB学习笔记:快速入门

    MongoDB学习笔记:快速入门   一.MongoDB 简介 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统.在高负载的情况下,添加更多的节点,可以保证服务器性能.M ...

  5. PHP操作MongoDB学习笔记

    <?php/*** PHP操作MongoDB学习笔记*///*************************//**   连接MongoDB数据库  **////*************** ...

  6. MongoDB学习笔记(三)--权限 && 导出导入备份恢复 && fsync和锁

    权限                                                                                             绑定内网I ...

  7. MongoDB学习笔记(1):MongoDB的安装和说明

    MongoDB学习笔记(1):MongoDB的安装和说明 快速开始 下载地址 官网下载: https://www.mongodb.com/download-center?jmp=nav#communi ...

  8. MongoDB学习笔记一:MongoDB的下载和安装

    MongoDB学习笔记一:MongoDB的下载和安装 趁着这几天比較空暇,准备学习一下MongoDB数据库.今天就简单的学习了一些MongoDB的下载和安装.并创建了存储MongoDB的数据仓库. 将 ...

  9. MongoDB学习笔记系列

    回到占占推荐博客索引 该来的总会来的,Ef,Redis,MVC甚至Sqlserver都有了自己的系列,MongoDB没有理由不去整理一下,这个系列都是平时在项目开发时总结出来的,希望可以为各位一些帮助 ...

  10. MongoDB 学习笔记(原创)

    MongoDB 学习笔记 mongodb 数据库 nosql 一.数据库的基本概念及操作 SQL术语/概念 MongoDB术语/概念 解释/说明 database database 数据库 table ...

随机推荐

  1. java使用JMail通过QQ邮件服务器实现自动发送邮件

    前言:项目开发的过程中,我们项目需要一个自动发送邮件提醒的小功能,于是简单的研究了一下java的JMail来实现自动发送邮件的功能.已被后期需要参考. 一.准备 实现的原理很简单:发送人 , 中转的邮 ...

  2. 重启Hbase命令

    注意先启动hadoop,记得重启zookeeper. 具体操作如下: cd hadoop-2.7.4/sbin/ && ./stop-all.sh && ./start ...

  3. 【Revit API】脱离中心文件

    话不多说,直接代码,整个过程不需要发起Transaction OpenOptions op = new OpenOptions(); op.Audit = true; //是否需要核查 op.Deta ...

  4. 各种蕴含算法思想的DP - 2

    study from: https://www.cnblogs.com/flashhu/p/9480669.html 3.斜率dp study from:http://www.cnblogs.com/ ...

  5. 目标检测评价指标(mAP)

    常见指标 precision 预测出的所有目标中正确的比例 (true positives / true positives + false positives). recall 被正确定位识别的目标 ...

  6. linux BASH shell下设置字体及背景颜色

    BASH shell下设置字体及背景颜色 echo -e "\e[31mtest\e[41m" \e[30m 将字符的显示颜色改为黑色 \e[31m 将字符的显示颜色改为红色 \e ...

  7. Spark记录-Scala函数

    Scala函数 Scala有函数和方法. Scala方法是一个具有名称和签名的类的一部分. Scala中的函数是一个可以分配给变量的完整对象. 函数定义可以出现在源文件中的任何位置. 不带参数的函数 ...

  8. bzoj千题计划205:bzoj3529: [Sdoi2014]数表

    http://www.lydsy.com/JudgeOnline/problem.php?id=3529 有一张n*m的数表,其第i行第j列(1 < =i < =n,1 < =j & ...

  9. unp学习笔记——Chapter1

    1.发现网络拓扑的几个重要的命令 (1).netstat -i 提供网络接口的信息.我们还指定-n 标志以输出数值地址,而不是试图把它们反向解析成名字.netstat -r 展示路由表. dzhwen ...

  10. Jquery 较好的效果

    仿google图片效果图片展示相册(jquery)的演示页面 产品相册展示插件slideshow多图可翻页 懒人建站 Jquery分享A Jquery分享B Jquery分享C Jquery分享D