本人使用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. 题解 P1184 【高手之在一起】

    好!机会来了! 依评论区的要求,小金羊献上STLset<string>的题解. 当然不会告诉你map<string,bool>我根本不会用 所以,有什么内置的成员函数救救孩子? ...

  2. 关于链表的总结(C++循环实现)

    0.目录 1.链表的基本操作 1.1 结点定义 1.2 创建链表 1.3 销毁链表 1.4 打印链表 1.5 获取链表长度 2.结点的基本操作 2.1 删除结点 2.2 查找结点 3.面试题 3.1 ...

  3. 【刷题】BZOJ 2734 [HNOI2012]集合选数

    Description <集合论与图论>这门课程有一道作业题,要求同学们求出{1, 2, 3, 4, 5}的所有满足以 下条件的子集:若 x 在该子集中,则 2x 和 3x 不能在该子集中 ...

  4. 以太坊 链私有链环境搭建(windows)

    摸索以太坊区块链技术几个月了.最近打算逐步的把自己学到的东西和大家分享一下.在阅读本文之前,希望大家能对区块链的概念能有所了解.这样操作过程中的环节理解更深入.下面开始进入准备.因为本次是window ...

  5. 论如何优雅的用bitset来求四维偏序

    四维偏序.. 就是给你一个四维集合.再给你一些询问,请你求出a[i].x1<=ask.x1&&a[i].x2<=ask.x2&&a[i].x3<=as ...

  6. bzoj1030: [JSOI2007]文本生成器(AC自动机+DP)

    第一次写这类题...懵 直接计算答案不好计算,所以补集转化求不合法的方案. 首先考虑朴素的DP,设$f(i, s)$表示前$i$个字符,字符串为$s$的方案数,且任意一个给定串都不存在$s$中. 我们 ...

  7. from表单文件上传后页面跳转解决办法

    from表单上传文件,路径跳转后,又不能转发回来. 本人的一个解决办法是.返回一段html代码,浏览器解析后后退一步,回到原来的页面并刷新. return "<html>< ...

  8. LeetCode 7最长公共前缀

    编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow" ...

  9. Kubernetes Pod详解

    目录 基本概念 pod资源配额 容器的健康检查 静态pod 基本概念 Pod是kubernetes集群中最基本的资源对象.每个pod由一个或多个业务容器和一个根容器(Pause容器)组成.Kubern ...

  10. python操作txt文件中数据教程[2]-python提取txt文件

    python操作txt文件中数据教程[2]-python提取txt文件中的行列元素 觉得有用的话,欢迎一起讨论相互学习~Follow Me 原始txt文件 程序实现后结果-将txt中元素提取并保存在c ...