因爲平常用到的都是Mysql關係數據庫,所以記錄一下使用java對mongodb數據庫進行基本操作的方法,便於以後撿起來。
public class UseJavaToMongodb
{
//mongodb保存的數據和關係數據庫不同,保存的是文檔類型(bson筆者導出數據到Excel就涉及到了這個格式)
//與json格式相同,都是鍵值對信息,比如關係數據庫裏面保存一個人的信息,表裏面有name,age,gender,address等字段
//在mongodb裏面就是一個文檔,文檔格式就是{"_id":"xxxxxxx","name":"xxx","age":16,"gender":"男","address":"xxxx"}
//_id這個字段是mongodb自動生成的,爲什麼mongodb保存數據量很大,但是查詢很快,就是因爲這個字段,他相當於map裏面的鍵
//根據這個_id字段可以唯一確定一個文檔,同時注意這個_id的類型是ObjectId類型,不是普通的字符串類型
//mongodb的集合,具體集合需要自己鏈接獲取,這裏就不寫明瞭
private MongoCollection<Document> collection;
//查詢
//一個條件
BasicDBObject oneCondition = new BasicDBObject();
oneCondtion.append("_id", new ObjectId("xxxx"));
collection.find(oneCondition);
//查詢
//多個條件,and或者or
BasicDBObject conditions = new BasicDBObject();
BasicDBList conditionList = new BasicDBList();
BasicDBObject condition1 = new BasicDBObject();
BasicDBObject condition2 = new BasicDBObject();
BasicDBObject condition3 = new BasicDBObject();
condition1.append("", "");
condition2.append("", "");
condition3.append("", "");
conditionList.add(condition1);
conditionList.add(condition2);
conditionList.add(condition3);
conditions.put("$and", conditionList);
Collection.find(conditions);
//刪除一個文檔
Document query = new Document();
query.put("_id", new ObjectId("xxxx"));
collection.deleteOne(query);
//保存文檔
Document data = new Document();
data.append("", "")
.append("", "")
.append("", "")
.append("", "")
.append("", "")
.append("", "")
.append("", "")
.append("", "")
collection.insertOne(data);
//更新一個文檔的一個或多個字段
//查找更新文檔的條件(如果根據這個條件找到多條記錄,只更新第一個,但是可以設置參數,更新所有的記錄)
Document searchQuery = new Document().append("_id", new ObjectId("xxxxxx"));
//需要修改的字段和修改之後字段的值都寫在這個Document裏面
Document updateDocument = new Document();
//mongodb更新字段用關鍵字$set,然後在後面加更新的字段的信息
//這裏注意使用了倆個Document來執行更新命令;
//如果只用一個Document,把$set和需要更新的所有字段和字段的值全放在一個Document裏面,那麼最後只會更新一個字段的值,就是最後一個字段的值
//筆者最開始也遇到了這個坑,目前還沒深入瞭解
Document updateDocumentAll = new Document();
updateDocument.append("":"")
.append("", "")
.append("", "")
.append("", "")
.append("", "")
.append("", "")
.append("", "")
updateDocumentAll.put("$set", updateDocument);
collection.updateOne(searchQuery, updateDocumentAll);
}