本人使用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. IntelliJ IDEA中文乱码问题

    转自  https://blog.csdn.net/m0_37893932/article/details/78280663 1 file->settings->appearence里面有 ...

  2. 洛谷P4301 [CQOI2013]新Nim游戏

    P4301 [CQOI2013]新Nim游戏 题目描述 传统的Nim游戏是这样的:有一些火柴堆,每堆都有若干根火柴(不同堆的火柴数量可以不同).两个游戏者轮流操作,每次可以选一个火柴堆拿走若干根火柴. ...

  3. 洛谷P4831 Scarlet loves WenHuaKe

    这道题告诉我们推式子的时候头要够铁. 题意 问一个\(n\times m\)的棋盘,摆上\(n\times 2\)个中国象棋的炮使其两两不能攻击的方案数,对\(998244353\)取模. \((n\ ...

  4. BZOJ5416 NOI2018冒泡排序(动态规划+组合数学)

    打表可以发现相当于不存在长度>=3的递减子序列. 考虑枚举在哪一位第一次不卡限制.注意到该位一定会作为前缀最大值.判掉已确定位不合法的情况后,现在的问题即为求长度为i.首位>j的合法排列个 ...

  5. Codeforces ECR50 div2题解

    A:签到 #include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> # ...

  6. mininet *** Error: RTNETLINK answers: No such file or directory 问题及解决方法

    一.问题 按照mininet官网中从源码安装步骤进行安装后,运行命令sudo mn --link tc,bw=10,提示说*** Error: RTNETLINK answers: No such f ...

  7. Spring点滴十一:Spring中BeanFactoryPostProcessor和BeanPostProcessor区别

    Spring中BeanFactoryPostProcessor和BeanPostProcessor都是Spring初始化bean时对外暴露的扩展点.两个接口从名字看起来很相似,但是作用及使用场景却不同 ...

  8. BZOJ2738 矩阵乘法 【整体二分 + BIT】

    题目链接 BZOJ2738 题解 将矩阵中的位置取出来按权值排序 直接整体二分 + 二维BIT即可 #include<algorithm> #include<iostream> ...

  9. 20145215卢肖明《网络对抗》逆向及Bof基础

    20145215卢肖明<网络对抗>逆向及Bof基础 实践目标 本次实践的对象是一个名为pwn1的linux可执行文件. 该程序正常执行流程是:main调用foo函数,foo函数会简单回显任 ...

  10. linux command ------ source

    source FileName 等效于. FileName,注 . 和 FileName 有空格 source命令也称为“点命令”,也就是一个点符号(.),作用是在当前bash环境下读取并执行File ...