MongoDB 3.x java基本操作-CRUD
MongoDB 3.x java基本操作
mongodbb版本:3.4
maven依賴:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
資料格式:
Connection工具類:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
public class Connection {
private static final String URI = "mongodb://userWords:[email protected]:27017/words";
private static MongoDatabase DB_CONNECTION = null;
private static MongoClient MONGO_CLIENT= null ;
public static MongoDatabase getDB(){
if(DB_CONNECTION != null && MONGO_CLIENT != null){
return DB_CONNECTION;
}
// 啟用了認證,如果不啟用,可以使用這種方式建立連線.
// MONGO_CLIENT = new MongoClient("127.0.0.1",27017);
MONGO_CLIENT = new MongoClient(new MongoClientURI(URI));
DB_CONNECTION = MONGO_CLIENT.getDatabase("words" );
return DB_CONNECTION;
}
public static void closeDBConntion(){
if(MONGO_CLIENT != null){
System.out.println("連線已關閉.");
MONGO_CLIENT.close();
}
}
public static void main(String[] args) {
}
}
CRUD:
插入:
package org.programming.mongodb.crud;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.programming.mongodb.Connection;
import org.programming.mongodb.Constant;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBInsert {
private MongoCollection<Document> collection;
public MongoDBInsert() {
MongoDatabase db = Connection.getDB();
collection = db.getCollection(Constant.COLLECTION_NAME);
}
public static void main(String[] args) {
MongoDBInsert mongo = new MongoDBInsert();
// mongo.addSelfie();
mongo.addGoogleAndTweet();
Connection.closeDBConntion();
}
/**
* @Title: addSelfie
* @Description: TODO 插入一個文件
* @date 2017年6月11日 下午3:07:03
* @return void
* @throws
*/
public void addSelfie(){
Document selfie = new Document("word","selefie");
selfie.append("first", "s").append("lase", "e");
selfie.append("size", 6).append("category", "New");
// selfie.append("leters", new String [] {"s","e", "l", "f", "i"});
selfie.append("leters", Arrays.asList("s","e", "l", "f", "i"));
Document stats = new Document("consontans", 3);
stats.append("vowels",3);
selfie.append("stats", stats);
Document cons = new Document("type","consontans");
// cons.append("chars", new String[] {"s", "l", "f"});
cons.append("chars", Arrays.asList("s", "l", "f"));
Document vowels = new Document("type","vowels");
// vowels.append("chars", new String[] {"e", "i"});
vowels.append("chars", Arrays.asList("e", "i"));
// Document [] charsets = new Document [] {cons,vowels};
List<Document> charsets = Arrays.asList(cons, vowels);
selfie.append("charsets", charsets);
try {
collection.insertOne(selfie);
System.out.println("插入成功");
} catch (Exception e) {
System.out.println("插入異常");
e.printStackTrace();
}
}
/**
* @Title: addGoogleAndTweet
* @Description: TODO 插入多個文件
* @date 2017年6月11日 下午3:06:45
* @return void
* @throws
*/
public void addGoogleAndTweet(){
Document google = new Document("word","google");
google.append("first", "g").append("last", "e").append("size", "6").append("category", "New").append("letters",Arrays.asList("g","o","l","e"));
Document stat = new Document("consonats",3).append("vowels", 3);
google.append("stats",stat);
Document cons = new Document("type", "consonants").append("chars", Arrays.asList("g","l"));
Document vowels = new Document("type", "vowels").append("chars", Arrays.asList("o","e"));
List<Document> charsets = Arrays.asList(cons, vowels);
google.append("charsets", charsets);
Document tweet = new Document("word","tweet");
tweet.append("first", "t").append("last", "t").append("size", "5").append("category", "New").append("letters",Arrays.asList("t","w","e"));
Document tstat = new Document("consonats",3).append("vowels", 2);
tweet.append("stats",tstat);
Document tcons = new Document("type", "consonants").append("chars", Arrays.asList("t","w"));
Document tvowels = new Document("type", "vowel").append("chars", Arrays.asList("e"));
List<Document> tcharsets = Arrays.asList(tcons, tvowels);
tweet.append("charsets", tcharsets);
collection.insertMany(Arrays.asList(google,tweet));
FindIterable<Document> queryResult= collection.find(new Document("category","New"));
MongoCursor< Document> cursor = queryResult.iterator();
while(cursor.hasNext()){
System.out.println(cursor.next());
}
}
}
package org.programming.mongodb.crud;
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Aggregates.*;
import java.util.Arrays;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.programming.mongodb.Connection;
import org.programming.mongodb.Constant;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class MongoDBSelect {
private MongoCollection<Document> collection;
public static void main(String[] args) {
MongoDBSelect mongo = new MongoDBSelect();
System.out.println("=============查詢一個=============");
mongo.getOne();
System.out.println("===========限制數量===========");
mongo.findLimit(1);
mongo.findLimit(4);
mongo.findLimit(6);
System.out.println("===========限制返回屬性===========");
mongo.includeFields(new String[] {});
mongo.includeFields(new String[] { "word" });
mongo.includeFields(new String[] { "word", "stats", "letters" });
mongo.excludeFields(new String[] { "charsets", "stats" });
System.out.println("===========分頁查詢===========");
mongo.findByPage(1, 10);
mongo.findByPage(2, 20);
mongo.findByPage(3, 5);
mongo.findByPage(4, 30);
System.out.println("==========聚合查詢============");
mongo.largeSmallWithVowels();
System.out.println("---------------------------");
mongo.Top10AvgWordFirst();
Connection.closeDBConntion();
}
public MongoDBSelect() {
MongoDatabase db = Connection.getDB();
collection = db.getCollection(Constant.COLLECTION_NAME);
}
public void getOne() {
Bson query = Filters.eq("first","k");
Document doc = collection.find(query).first();
System.out.println(doc.toJson());
}
/**
* @Title: findLimit
* @Description: TODO 限制返回的文件數量
* @date 2017年6月11日 上午9:36:23
* @return void
* @throws
*/
public void findLimit(int limit) {
Document query = new Document("first", "s");
MongoCursor<Document> cursor = collection.find(query).limit(limit).iterator();
StringBuilder sb = new StringBuilder();
while (cursor.hasNext()) {
Document doc = cursor.next();
sb.append(" " + doc.get("word").toString());
}
String words = sb.toString();
if (sb.length() > 80) {
words = sb.substring(0, 80);
}
System.out.println(words);
}
/**
* @Title: inlcudeFields
* @Description: TODO 限定返回欄位
* @date 2017年6月11日 上午10:06:28
* @param fields 包含的欄位.
* @return void
* @throws
*/
public void includeFields(String[] fields) {
Document query = new Document("first", "h");
Document fieldDoc = new Document();
for (String field : fields) {
fieldDoc.append(field, 1);
}
MongoCursor<Document> cursor = collection.find(query).projection(fieldDoc).limit(2).iterator();
System.out.println("包含 " + Arrays.toString(fields) + " 欄位");
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
}
/**
* @Title: excludeFields
* @Description: TODO 限定返回欄位
* @date 2017年6月11日 上午10:15:40
* @param fields 不包含的欄位.
* @return void
* @throws
*/
public void excludeFields(String[] fields) {
Document query = new Document("first", "h");
Document fieldDoc = new Document();
for (String field : fields) {
fieldDoc.append(field, 0);
}
MongoCursor<Document> cursor = collection.find(query).projection(fieldDoc).limit(2).iterator();
System.out.println("不包含 " + Arrays.toString(fields) + " 欄位");
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
}
/**
* @Title: findByPage
* @Description: TODO 分頁查詢
* @date 2017年6月11日 上午10:19:59
* @param page 單前頁碼
* @param pageSize 每頁最大文件數
* @return void
* @throws
*/
public void findByPage(int page, int pageSize) {
Document query = new Document("first", "h");
Document fieldDoc = new Document();
fieldDoc.append("word", 1);
fieldDoc.append("letters", 1);
MongoCursor<Document> cursor = collection.find(query).projection(fieldDoc).limit(pageSize)
.skip((page - 1) * page).iterator();
System.out.println(String.format("當前頁碼:%d,當前頁最大文件數:%d", page, pageSize));
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
}
/**
* @Title: firstIsAAndLastIsVowel
* @Description: TODO 分組查詢 .mongodb 3.x中沒有查到group 方法.
* @date 2017年6月11日 上午11:45:52
* @return void
* @throws
*/
public void firstIsAAndLastIsVowel() {
}
/**
* @Title: largeSmallvowels
* @Description: TODO 聚合.每種母音字母開頭的單詞中最大和最短長度.
* @date 2017年6月11日 上午11:47:38
* @return void
* @throws
*/
public void largeSmallWithVowels() {
Bson match = match(in("first", Arrays.asList("a", "e", "i", "o", "u")));
Bson group = group("$first", max("largest", "$size"), min("smallest", "$size"), sum("total", "$size"));
Bson sort = sort(new Document("_id", 1));
AggregateIterable<Document> result = collection.aggregate(Arrays.asList(match, group, sort));
MongoCursor<Document> cursor = result.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
}
/**
* @Title: Top10AvgWordFirst
* @Description: TODO 聚合.每種字母開頭的單詞中平均長度最長的10個.
* @date 2017年6月11日 上午11:54:36
* @return void
* @throws
*/
public void Top10AvgWordFirst() {
Bson group = group("$first", avg("avegrage", "$size"));
Bson sort = sort(new Document("avegrage", -1));
Bson limit = limit(10);
AggregateIterable<Document> result = collection.aggregate(Arrays.asList(group, sort, limit));
MongoCursor<Document> cursor = result.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
}
}
更新
package org.programming.mongodb.crud;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.programming.mongodb.Connection;
import org.programming.mongodb.Constant;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class MongoDBUpdate {
public static void main(String[] args) {
MongoDBUpdate mongo = new MongoDBUpdate();
System.out.println("========更新之前=============");
mongo.showWord();
mongo.updateDoc();
System.out.println("\n--------更新之後-------------");
mongo.showWord();
mongo.resetDoc();
System.out.println("\n--------reset之後------------");
mongo.showWord();
System.out.println("\n========批量更新=============");
System.out.println("\n========批量更新之前=============");
mongo.showWords();
mongo.updateStartWithH();
System.out.println("\n--------updateMany之前------------");
mongo.showWords();
mongo.resetStartWithH();
System.out.println("\n--------updateMany之後------------");
mongo.showWords();
System.out.println("\n=========replace============");
mongo.showWordOcean("--------replace 之前----------");
mongo.saveBlueDoc();
mongo.showWordOcean("--------replace 之後----------");
mongo.showWordOcean("--------replace 之前----------");
mongo.resetBlueDoc();
mongo.showWordOcean("--------replace 之後----------");
Connection.closeDBConntion();
}
private MongoCollection<Document> collection;
public MongoDBUpdate() {
MongoDatabase db = Connection.getDB();
collection = db.getCollection(Constant.COLLECTION_NAME);
}
public void saveBlueDoc(){
Document query = new Document("word","ocean");
Document doc = collection.find(query).iterator().next();
doc.put("category", "blue");
collection.replaceOne(query, doc);
}
public void resetBlueDoc(){
Document query = new Document("word","ocean");
Document doc = collection.find(query).iterator().next();
doc.put("category", "");
collection.replaceOne(query, doc);
}
public void showWord(String msg){
System.out.println("\n" + msg);
Document query = new Document("word","ocean");
MongoCursor<Document> cursor = collection.find(query).projection(new Document("word",1).append("category", 1)).iterator();
while(cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}
/**
* @Title: updateDoc
* @Description: TODO 把left 改成lefty
* @date 2017年6月11日 下午4:09:12
* @return void
* @throws
*/
public void updateDoc(){
Document query = new Document("word","left");
// Bson update = set("word", "left");
Document update = new Document("$set",new Document("word","lefty")).append("$inc",new Document("size",1))
.append("$push", new Document("letters","y"));
collection.updateOne(query, update);
}
/**
* @Title: resetDoc
* @Description: TODO 把lefty 改成left
* @date 2017年6月11日 下午4:29:20
* @return void
* @throws
*/
public void resetDoc(){
Document query = new Document("word","lefty");
// Bson update = set("word", "left");
Document update = new Document("$set",new Document("word","left")).append("$inc",new Document("size",-1))
.append("$pop", new Document("letters","1"));
collection.updateOne(query, update);
}
/**
* @Title: updateStartWithH
* @Description: TODO 批量更新
* @date 2017年6月11日 下午4:53:10
* @return void
* @throws
*/
public void updateStartWithH(){
Bson query = Filters.eq("first", "h");
Document update = new Document("$set", new Document("category","New"));
collection.updateMany(query, update);
}
/**
* @Title: resetStartWithH
* @Description: TODO 批量更新,刪除屬性
* @date 2017年6月11日 下午4:53:34
* @return void
* @throws
*/
public void resetStartWithH(){
Bson query = Filters.eq("first", "h");
Document update = new Document("$unset", new Document("category",""));
collection.updateMany(query, update);
}
public void showWord(){
Bson query = Filters.in("word","left","lefty");
MongoCursor<Document> cursor = collection.find(query).iterator();
while(cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}
public void showWords(){
Document query = new Document("first","h").append("last", "h");
MongoCursor<Document> cursor = collection.find(query).projection(new Document("word", 1).append("category", 1)).iterator();
while(cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}
public void showWordOcean(String msg){
System.out.println("\n" + msg);
Document query = new Document("word","ocean");
MongoCursor<Document> cursor = collection.find(query).projection(new Document("word",1).append("category", 1)).iterator();
while(cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}
}
刪除
“`
package org.programming.mongodb.crud;
import org.bson.Document;
import org.programming.mongodb.Connection;
import org.programming.mongodb.Constant;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBDelete {
private MongoCollection collection;
public static void main(String[] args) {
MongoDBDelete mongo = new MongoDBDelete();
System.out.println(“============刪除前==========”);
mongo.showNewDocs();
mongo.deleteNewDocs();
System.out.println(“============刪除後==========”);
mongo.showNewDocs();
}
public MongoDBDelete() {
MongoDatabase db = Connection.getDB();
collection = db.getCollection(Constant.COLLECTION_NAME);
}
public void deleteNewDocs(){
Document query = new Document("category","New");
collection.deleteMany(query);
}
public void showNewDocs(){
FindIterable<Document> queryResult= collection.find(new Document("category","New"));
MongoCursor< Document> cursor = queryResult.iterator();
while(cursor.hasNext()){
System.out.println(cursor.next());
}
}
}
.