Mongo DB Java操做

一、首先下載Mongo DB java 驅動java

 

二、操做Mongo 增刪改查git

package com.sjjy.mongo;github

import java.util.ArrayList;
import java.util.List;mongodb

import org.bson.Document;數據庫

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;app

public class MongoTest {

public static void main(String[] args) {

try{

//鏈接到Mongo服務
MongoClient mongoClient = new MongoClient("localhost", 27017);
//鏈接到數據庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("cf_sjjy_mongo");

System.out.println("Connect to database successfully");
mongoDatabase.createCollection("test");
System.out.println("集合建立成功");

MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 選擇成功");

//插入文檔
/**
* 1. 建立文檔 org.bson.Document 參數爲key-value的格式
* 2. 建立文檔集合List<Document>
* 3. 將文檔集合插入數據庫集合中 mongoCollection.insertMany(List<Document>) 插入單個文檔能夠用 mongoCollection.insertOne(Document)
* */
Document document = new Document("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("by", "Fly");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);
System.out.println("文檔插入成功");

//檢索全部文檔
/**
* 1. 獲取迭代器FindIterable<Document>
* 2. 獲取遊標MongoCursor<Document>
* 3. 經過遊標遍歷檢索出的文檔集合
* */
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
//獲取文檔對象
System.out.println(mongoCursor.next());
//獲取文檔對象裏面的一個屬性值
System.out.println(mongoCursor.next().get("likes"));
}


//更新文檔 將文檔中likes=100的文檔修改成likes=200
collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
//檢索查看結果
 FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());



//刪除符合條件的第一個文檔
collection.deleteOne(Filters.eq("likes", 100));
//刪除全部符合條件的文檔
collection.deleteMany (Filters.eq("likes", 200));
//檢索查看結果
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next() + " wenhy");
}


}catch (Exception e) {

System.out.println(e.getClass().getName() + " : " + e.getMessage());ui

}
}對象

}blog

 

更多操做能夠參考:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/ip

相關文章
相關標籤/搜索