MongoDB学习笔记-2(使用java连接Mongo)
本人使用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)的更多相关文章
- [Spring Data MongoDB]学习笔记--注册一个Mongo实例
1. 通过Java based bean metadata @Configuration public class AppConfig { public @Bean Mongo mongo() thr ...
- mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)
最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...
- 【转】mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)
mongoDB 学习笔记纯干货(mongoose.增删改查.聚合.索引.连接.备份与恢复.监控等等) http://www.cnblogs.com/bxm0927/p/7159556.html
- MongoDB学习笔记:快速入门
MongoDB学习笔记:快速入门 一.MongoDB 简介 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统.在高负载的情况下,添加更多的节点,可以保证服务器性能.M ...
- PHP操作MongoDB学习笔记
<?php/*** PHP操作MongoDB学习笔记*///*************************//** 连接MongoDB数据库 **////*************** ...
- MongoDB学习笔记(三)--权限 && 导出导入备份恢复 && fsync和锁
权限 绑定内网I ...
- MongoDB学习笔记(1):MongoDB的安装和说明
MongoDB学习笔记(1):MongoDB的安装和说明 快速开始 下载地址 官网下载: https://www.mongodb.com/download-center?jmp=nav#communi ...
- MongoDB学习笔记一:MongoDB的下载和安装
MongoDB学习笔记一:MongoDB的下载和安装 趁着这几天比較空暇,准备学习一下MongoDB数据库.今天就简单的学习了一些MongoDB的下载和安装.并创建了存储MongoDB的数据仓库. 将 ...
- MongoDB学习笔记系列
回到占占推荐博客索引 该来的总会来的,Ef,Redis,MVC甚至Sqlserver都有了自己的系列,MongoDB没有理由不去整理一下,这个系列都是平时在项目开发时总结出来的,希望可以为各位一些帮助 ...
- MongoDB 学习笔记(原创)
MongoDB 学习笔记 mongodb 数据库 nosql 一.数据库的基本概念及操作 SQL术语/概念 MongoDB术语/概念 解释/说明 database database 数据库 table ...
随机推荐
- download & excel & blob
download & excel & blob Blob https://developer.mozilla.org/en-US/docs/Web/API/Blob FileReade ...
- Delphi用户登录窗口框架
经常看到一些新手在CSDN上问登录窗口如何写,也看到N多人form1.show/form1.create/…中做form2.show之类.实在看不下去了.这种写法实在不是很好,于是还是把自己理解的登录 ...
- MT【102】一个常见的因式分解公式
解答: $x^3+y^3+1-3xy=(x+y+1)(x^2+y^2+1+xy-x-y)=$ $(x+y+1)(x^2+y^2+1+xy-x-y)=$ $\frac{1}{2}(x+y+1)[(x-y ...
- 「TJOI / HEOI2016」字符串
「TJOI / HEOI2016」字符串 题目描述 佳媛姐姐过生日的时候,她的小伙伴从某东上买了一个生日礼物.生日礼物放在一个神奇的箱子中.箱子外边写了一个长为 \(n\) 的字符串 \(s\),和 ...
- 【题解】 [ZJOI2009]假期的宿舍 (二分图匹配)
懒得复制题面,戳我 Solution: 处理出床位.要留校的人(注意来访问的人一定住校),和人与人的关系(连边) 再接着就是二分图. 注意的就是连向的人必须是有床位的 还要注意的就是只用判断住校的同学 ...
- 洛谷P2605 基站选址
神TM毒瘤线段树优化DP......新姿势get. 题意:有n个村庄,在里面选不多于k个建立基站. 建立基站要ci的费用.如果一个村庄方圆si内没有基站,那么又要支出wi的费用.求最小费用. 解:很显 ...
- NO.1: 视C++为一个语言联邦
C++由4个部分组成: 1.C part of C++; 2.Object-Oriented C++; 3.Template C++; 4.STL 请记住:C++的高效编程视状况而变化,取决你使用C+ ...
- Json对象和Json字符串的区别
说白了,字符串都是带引号的. 尤其是在使用springmvc的时候,后台@RequestBody接受的是一个json格式的字符串,一定是一个字符串. 参考这个博客还可以: https://blog. ...
- Jenkins + Pipeline 构建流水线发布
Jenkins + Pipeline 构建流水线发布 利用Jenkins的Pipeline配置发布流水线 参考: https://jenkins.io/doc/pipeline/tour/depl ...
- 函数和常用模块【day06】:json模块(十一)
本节内容 1.dumps序列化和loads反序列化 2.dump序列化和load反序列化 3.序列函数 1.dumps序列化和loads反序列化 dumps()序列化 1 2 3 4 5 6 7 8 ...