目錄mongodb
該類是emessage自定義的一個類,用於對mongodb進行操做,能夠對mongodb進行插入,修改與刪除。該類是一個單例數據庫
該類主要用來設置一些鏈接參數,與設置用戶名和密碼(若是須要),並獲取對應的數據庫app
private MongoManager() { //這裏設置了MongoClient鏈接池的各類配置 MongoClientOptions options = MongoClientOptions.builder() .connectionsPerHost(MongoConfig.connectionsPerHost) .maxWaitTime(MongoConfig.maxWaitTime) .socketTimeout(MongoConfig.socketTimeout) .maxConnectionLifeTime(MongoConfig.maxConnectionLifeTime) .connectTimeout(MongoConfig.connectTimeout).build(); //使用身份驗證a if(MongoConfig.authentication.equals("1")){ //createMongoCRCredential是使用身份驗證的方法 List<MongoCredential> lstCredentials = Arrays.asList(MongoCredential.createMongoCRCredential( MongoConfig.username, "emessage", MongoConfig.password.toCharArray())); //經過傳入lstCredentials來傳入身份驗證 mg = new MongoClient(new ServerAddress(MongoConfig.host,MongoConfig.port),lstCredentials,options); }else{ mg = new MongoClient(new ServerAddress(MongoConfig.host,MongoConfig.port),options); } //獲取對應的數據庫 mongoDatabase = mg.getDatabase("emessage"); }
public static MongoManager getInstance() { if(instance==null){ int ret = MongoConfig.loadMongoConfig(); if (0 != ret) { return null; }else{ instance = new MongoManager(); instance.initMongo(); } } return instance; }
該方法控制該類是一個單例,若是ret=0,則讀取配置文件正常,initMongo,則是獲取對應數據庫中的全部集合。
該方法獲取一個MongoManager對象,並獲取對應數據庫中的全部集合dom
private void initMongo(){ MongoCollection<Document> collection = mongoDatabase.getCollection(MongoColl.HISTORYMSG.text); }
表示獲取MongoColl.HISTORYMSG.text數據庫中的全部集合socket
經過傳入的集合名獲取給定的集合ui
public MongoCollection<Document> getCollection(MongoColl mongoColl) { //獲取給定的集合 MongoCollection<Document> collection = mongoDatabase.getCollection(mongoColl.text); return collection; }
向數據庫對應的集合中插入一條數據this
public void insertDocument(MongoColl mongoColl,Document document){ MongoCollection<Document> coll = getCollection(mongoColl); //向數據庫中插入一條數據 coll.insertOne(document); }
應用
插入一條數據code
Document document = new Document(); document.put("name", "wyj"); document.put("sex", "1"); MongoManager m = MongoManager.getInstance(); m.insertDocument(MongoManager.MongoColl.HISTORYMSG, document);
public static enum MongoColl { HISTORYMSG("emessage"), HISTORYMSGRESENTLY("historymsgresently"),SOCIALHISTORYMSGRIGHT("social_historymsgright"); private final String text; private MongoColl(final String text){ this.text=text; } public String getText(){ return text ; } }
批量插入數據對象
public void insertDocuments(MongoColl mongoColl,List<Document> documents){ MongoCollection<Document> coll = getCollection(mongoColl); coll.insertMany(documents); }
應用排序
public void insert(){ MongoManager mongoManager = MongoManager.getInstance(); List<Document> list = new ArrayList<>(); String name = "huye"; String age = ""; for (int i=0; i<10; i++){ Document document = new Document(); age = String.valueOf(10+Math.random()*20); document.put("name",name); document.put("age",age); list.add(document); } //批量插入 mongoManager.insertDocuments(MongoManager.MongoColl.HISTORYMSG,list); }
public UpdateResult update(MongoColl mongoColl,Bson filter,Bson update){ MongoCollection<Document> coll = mongoDatabase.getCollection(mongoColl.text); coll.updateMany(filter, update) ; return coll.updateMany(filter, update); }
應用
public void update(){ MongoManager mongoManager = MongoManager.getInstance(); //這裏講包含name字段的數據,有sex就將sex修改成"sex" : { "sex" : "1" },沒有改字段則新加一個改字段 //Document document = new Document("$set",new Document("sex",new Document("sex","1"))); //UpdateResult updateResult = mongoManager.update(MongoManager.MongoColl.HISTORYMSG,Filters.exists("name",true),document); //這裏講sex的內容修改成222 Document document = new Document("$set",new Document("sex","222")); UpdateResult updateResult = mongoManager.update(MongoManager.MongoColl.HISTORYMSG,Filters.exists("name",true),document); System.out.println("修改值的數目:"+updateResult.getUpsertedId()); }
Java中能夠經過updateOne,updateMany,replaceOne方法進行集合的文檔更新。可是 _id 是不能更新的
updateOne只會更新一條數據,即便經過Filters.lt("age", 20)過濾出多條數據,也只會取出一條進行更新
名稱 | 描述 |
---|---|
$inc | 增長一個指定值 |
$mul | 乘以一個指定值 |
$rename | 重命名 |
$setOnInsert | 更新操做對現有的文檔沒有影響,而是新插入了一個文檔,則在這新插入的文檔中加上指定字段 |
$set | 修改值 |
$unset | 刪除文檔中指定字段 |
$min | 更新文檔中小於指定值的字段 |
$max | 更新文檔中大於指定值的字段 |
$currentDate | 設置當前時間,日期或者時間戳 |
只修改指定字段值,當字段不存在時,則在該文檔中添加一個新的字段並賦值
doc.updateOne(Filters.eq("age", 20), new Document("$set",new Document("sex",2222)));
FindIterable
iter1.forEach(new Block
public void apply(Document _doc) {
System.out.println(_doc.toJson());
}
});
對指定字段進行增量增長,當字段不存在時,則在該文檔中添加字段並賦值
doc.updateOne(Filters.eq("name", "張三"), new Document("$inc",new Document("age",10)));
FindIterable
iter.forEach(new Block
public void apply(Document _doc) {
System.out.println(_doc.toJson());
}
});
$mul的用法與$inc的用法差很少,差異在於$mul爲相乘,$inc爲相加,若字段不存在,添加字段並賦值爲0
修改document的字段名
doc.updateOne(Filters.eq("name", "張三"), new Document("$rename",new Document("phone","telPhone")));
FindIterable
iter.forEach(new Block
public void apply(Document _doc) {
System.out.println(_doc.toJson());
}
});
public DeleteResult remove(MongoColl mongoColl, Bson filter) { MongoCollection<Document> coll = mongoDatabase.getCollection(mongoColl.text); return coll.deleteMany(filter); }
應用
public void remove(){ MongoManager mongoManager = MongoManager.getInstance(); DeleteResult deleteResult = mongoManager.remove(MongoManager.MongoColl.HISTORYMSG,Filters.eq("name","huye")); System.out.println("刪除數據條數:"+deleteResult.getDeletedCount()); }
public MongoCursor<Document> find(MongoColl mongoColl, Bson filter) { //經過傳入的集合名找到對應的集合 MongoCollection<Document> coll = mongoDatabase.getCollection(mongoColl.text); //經過傳入的filter,來查找集合內對應的內容 return coll.find(filter).iterator(); } //表示按照Bson字段排序,取值爲Sorts.ascending(_id):表示按照_id字段升序 //limit:表示顯示幾列數據 public MongoCursor<Document> find(MongoColl mongoColl, Bson filter,Bson sort,int limit) { MongoCollection<Document> coll = mongoDatabase.getCollection(mongoColl.text); return coll.find(filter).sort(sort).limit(limit).iterator() ; }
應用
public void find(){ MongoManager mongoManager = MongoManager.getInstance(); // 該類經過排序來查找對應的數據 // Sorts.ascending(_id):表示按照_id字段升序 // 2:表示顯示兩列數據 String _id = "_id"; //MongoCursor mongoCursor = MongoManager.getInstance().find(MongoManager.MongoColl.HISTORYMSG,Filters.eq("name","wyj"), Sorts.ascending(_id),2); //查詢字段名爲name的全部內容,true:表示包含有字段名爲name的值,false表示不包含有字段名爲name的值 MongoCursor mongoCursor = mongoManager.find(MongoManager.MongoColl.HISTORYMSG,Filters.exists("name",false)); while(mongoCursor.hasNext()){ Document document = (Document) mongoCursor.next(); System.out.println(document.toString()); } }