標籤:lan end over 版本 odata width city ted list
環境配置:在 Java 程式中如果要使用 MongoDB,你需要確保已經安裝了 Java 環境及 MongoDB JDBC 驅動。
首先你必須下載mongo jar包,:http://mongodb.github.io/mongo-java-driver/, 請確保下載最新版本。
https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/
Hello MongoDB -- Java編程DEMO:
package com.xctdemo.main;import java.util.ArrayList;import java.util.List;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;public class HelloMongoDB { public static void main(String[] args) { System.out.println("---- Hello MongoDB ----"); try { // 串連到 mongodb 服務 MongoClient mongoClient = new MongoClient("localhost", 27017); // 串連到資料庫 MongoDatabase mongoDatabase = mongoClient.getDatabase("world"); System.out.println("Connect to database successfully"); /* * mongoDatabase.createCollection("city"); * System.out.println("集合city建立成功"); // */ // 擷取集合 MongoCollection<Document> collection = mongoDatabase .getCollection("city"); System.out.println("集合 city 選擇成功"); // 在集合中插入文檔 /** * 1. 建立文檔 org.bson.Document 參數為key-value的格式 2. 建立文檔集合List<Document> * 3. 將文檔集合插入資料庫集合中 mongoCollection.insertMany(List<Document>) * 插入單個文檔可以用 mongoCollection.insertOne(Document) * */ Document document = new Document("name", "beijing") .append("country", "china").append("provice", "BEIJING") .append("people-count", 1000); List<Document> documents = new ArrayList<Document>(); documents.add(document); collection.insertMany(documents); System.out.println("文檔插入成功-Many"); Document mydocument = new Document("name", "washington") .append("country", "america") .append("provice", "WASHINGTON") .append("people-count", 1200); collection.insertOne(mydocument); System.out.println("文檔插入成功-One"); // 檢索所有文檔 showDocuments(collection); // 刪除合格第一個文檔 // collection.deleteOne(Filters.eq("name", "beijing")); // 刪除所有合格文檔 collection.deleteMany(Filters.eq("name", "beijing")); System.out.println("---- deleted OK ----"); System.out.println("--------------------------"); // 更新文檔 將文檔中likes=100的文檔修改為likes=200 collection.updateMany(Filters.eq("name", "washington"), new Document("$set", new Document("country", "JAPAN"))); // 檢索所有文檔 showDocuments(collection); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } System.out.println("---- over ----"); } private static void showDocuments(MongoCollection<Document> collection) { /** * 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()); // .get("name") } }}
Hello MongoDB -- Java編程