最近做項目想用一下NoSQL數據庫,由於項目需要保存大量的json數據,我就選了MongoDB作爲我的數據庫。
最新版爲3.0 下載安裝都很容易,今天按照教程一步一步實現了增刪改查等工作,本文將把要用到的代碼都貼上來而且都做好中文註釋方便大家閱讀。
過程中發現兩處不能使用教程中的代碼實現的地方,經過查資料已經用另外的方法實現了,不知道是不是叫承重的代碼出錯了還是什麼原因,如果有知道的朋友請留言告訴我,多謝~
官方教程鏈接:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/
如果不用maven附件中提供了已經下好的java驅動
- package com.zhongli.TwitterGetter.app;
- import java.util.*;
- import org.bson.Document;
- import org.bson.conversions.Bson;
- import com.mongodb.BasicDBObject;
- import com.mongodb.Block;
- import com.mongodb.MongoClient;
- import com.mongodb.client.*;
- import com.mongodb.client.model.BulkWriteOptions;
- import com.mongodb.client.model.DeleteOneModel;
- import com.mongodb.client.model.InsertOneModel;
- import com.mongodb.client.model.ReplaceOneModel;
- import com.mongodb.client.model.UpdateOneModel;
- import com.mongodb.client.result.DeleteResult;
- import com.mongodb.client.result.UpdateResult;
- import static com.mongodb.client.model.Filters.*;
- /**
- * 程序入口
- *
- * @author John
- *
- */
- public class testmain {
- public static void main(String[] args) {
- testmain tm = new testmain();
- tm.test();
- }
- /**
- * test
- */
- private void test() {
- // 獲取鏈接
- MongoClient mongoClient = new MongoClient("localhost", 27017);
- // 獲取數據庫
- MongoDatabase database = mongoClient.getDatabase("mydb");
- // 進入某個文檔集
- MongoCollection<Document> collection = database.getCollection("test");
- /********************** 數據插入 ****************************/
- // // 創建新文檔
- // Document doc = new Document("name", "MongoDB")
- // .append("type", "database").append("count", 1)
- // .append("info", new Document("x", 203).append("y", 102));
- // // 將文檔插入文檔集合
- // collection.insertOne(doc);
- //
- // // 創建一個包含多個文檔的列表
- // List<Document> documents = new ArrayList<Document>();
- // for (int i = 0; i < 100; i++) {
- // documents.add(new Document("i", i));
- // }
- // // 向文檔中插入列表
- // collection.insertMany(documents);
- /***************** 數據讀取 ****************************************/
- // // 顯示集合中的文檔的數量
- // System.out.println(collection.count());
- //
- // // 查詢集合中的第一個文檔
- // Document myDoc = collection.find().first();
- // System.out.println(myDoc.toJson());
- //
- // //獲取集合中的全部文檔
- // MongoCursor<Document> cursor = collection.find().iterator();
- // try {
- // while (cursor.hasNext()) {
- // System.out.println(cursor.next().toJson());
- // }
- // } finally {
- // cursor.close();
- // }
- // //獲取全部文檔的另一種方法
- // for (Document cur : collection.find()) {
- // System.out.println(cur.toJson());
- // }
- // // 根據條件獲取某分文檔 eq:==
- // Document myDoc = collection.find(eq("i", 71)).first();
- // System.out.println(myDoc.toJson());
- // 通過查詢語句一次性獲取多個數據
- // Block<Document> printBlock = new Block<Document>() {
- // @Override
- // public void apply(final Document document) {
- // System.out.println(document.toJson());
- // }
- // };
- // 獲得所有大於50的
- // collection.find(gt("i", 50)).forEach(printBlock);
- // 大於50 小於 100
- // collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
- // 對輸出文檔進行排序,-1爲遞減,1爲遞增
- // 官方文檔的例子有誤:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#sorting-documents
- // Document myDoc = collection.find(exists("i"))
- // .sort(new BasicDBObject("i", -1)).first();
- // System.out.println(myDoc.toJson());
- // 選擇性輸出結果中的元素,0爲不顯示,1爲顯示
- // 官方文檔中的例子又不能用:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#projecting-fields
- // BasicDBObject exclude = new BasicDBObject();
- // exclude.append("_id", 0);
- // // exclude.append("count", 0);
- // exclude.append("name", 1);
- // exclude.append("info", 1);
- // Document myDoc = collection.find().projection(exclude).first();
- // System.out.println(myDoc.toJson());
- /************************* 修改數據庫中數據 *************************************/
- // 修改時的參數:
- // $inc 對指定的元素加
- // $mul 乘
- // $rename 修改元素名稱
- // $setOnInsert 如果以前沒有這個元素則增加這個元素,否則不作任何更改
- // $set 修改制定元素的值
- // $unset 移除特定的元素
- // $min 如果原始數據更大則不修改,否則修改爲指定的值
- // $max 與$min相反
- // $currentDate 修改爲目前的時間
- // //修改第一個符合條件的數據
- // $set 爲修改
- // collection.updateOne(eq("i", 10), new Document("$set", new
- // Document("i", 110)));
- // // 獲取全部文檔,可以看到以前10的地方變成了110
- // for (Document cur : collection.find()) {
- // System.out.println(cur.toJson());
- // }
- // 批量修改數據並且返回修改的結果,講所有小於100的結果都加100
- // UpdateResult updateResult = collection.updateMany(lt("i", 100),
- // new Document("$inc", new Document("i", 100)));
- // // 顯示發生變化的行數
- // System.out.println(updateResult.getModifiedCount());
- // // 獲取全部文檔,可以看到除了剛纔修改的110其他的全爲了100
- // for (Document cur : collection.find()) {
- // System.out.println(cur.toJson());
- // }
- /************************** 刪除數據 *****************************/
- // 刪除第一個符合條件的數據
- // collection.deleteOne(eq("i", 110));
- // // 獲取全部文檔,可以看到沒有110這個數了
- // for (Document cur : collection.find()) {
- // System.out.println(cur.toJson());
- // }
- // 刪除所有符合條件的數據,並且返回結果
- // DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
- // // 輸出刪除的行數
- // System.out.println(deleteResult.getDeletedCount());
- // // 獲取全部文檔,所有i>=100的數據都沒了
- // for (Document cur : collection.find()) {
- // System.out.println(cur.toJson());
- // }
- /*************************** 程序塊,一次執行多條語句 ********************************/
- // 按照語句先後順序執行
- // collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(
- // "_id", 4)), new InsertOneModel<>(new Document("_id", 5)),
- // new InsertOneModel<>(new Document("_id", 6)),
- // new UpdateOneModel<>(new Document("_id", 1), new Document(
- // "$set", new Document("x", 2))), new DeleteOneModel<>(
- // new Document("_id", 2)),
- // new ReplaceOneModel<>(new Document("_id", 3), new Document(
- // "_id", 3).append("x", 4))));
- // // 獲取全部文檔
- // for (Document cur : collection.find()) {
- // System.out.println(cur.toJson());
- // }
- // 不按照語句先後順序執行
- // collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(
- // "_id", 4)), new InsertOneModel<>(new Document("_id", 5)),
- // new InsertOneModel<>(new Document("_id", 6)),
- // new UpdateOneModel<>(new Document("_id", 1), new Document(
- // "$set", new Document("x", 2))), new DeleteOneModel<>(
- // new Document("_id", 2)),
- // new ReplaceOneModel<>(new Document("_id", 3), new Document(
- // "_id", 3).append("x", 4))), new BulkWriteOptions()
- // .ordered(false));
- // 獲取全部文檔
- // for (Document cur : collection.find()) {
- // System.out.println(cur.toJson());
- // }
- // 關閉數據庫連接
- mongoClient.close();
- }
- }