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

posted @ 2017-11-14 13:00  小炮先生  阅读(893)  评论(0编辑  收藏  举报