您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Java中怎么獲取MongoDB連接,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
首先是所需jar包,Maven中的配置如下:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.4.1</version></dependency><dependency> <groupId>org.mongodb</groupId> <artifactId>bson</artifactId> <version>3.4.1</version></dependency><dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.7.0.RELEASE</version></dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.9.1</version></dependency>
獲取連接的代碼如下(本中用的是模板類):
List<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(new ServerAddress(dataSource.getSourceIp(), Integer.valueOf(dataSource.getSourcePort())));List<MongoCredential> credentials = new ArrayList<MongoCredential>();credentials.add(MongoCredential.createScramSha1Credential(dataSource.getUsername(), dataSource.getSourceName(), dataSource.getPassword().toCharArray()));MongoClient mongoClient = new MongoClient(addrs, credentials);MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, dataSource.getSourceName());MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);mongoTemplate.getCollectionNames();
或者用如下方式獲取:
ServerAddress serverAddress = new ServerAddress("192.168.16.121",27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三個參數分別為 用戶名 數據庫名稱 密碼 MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "123456Ab".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //通過連接認證獲取MongoDB連接 MongoClient mongoClient = new MongoClient(addrs,credentials); //連接到數據庫 MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");mongoDatabase.getCollection("test").find().iterator();// 關閉數據庫連接mongoClient.close();
附帶簡單增刪改查的例子:
package test; import java.util.ArrayList;import java.util.HashMap;import java.util.List; import org.junit.Test;import org.springframework.data.domain.Sort;import org.springframework.data.mongodb.MongoDbFactory;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.SimpleMongoDbFactory;import org.springframework.data.mongodb.core.query.Criteria;import org.springframework.data.mongodb.core.query.Query;import org.springframework.data.mongodb.core.query.Update; import com.mongodb.MongoClient;import com.mongodb.MongoCredential;import com.mongodb.ServerAddress;import com.mongodb.WriteResult; import bean.Book;import bean.Good;import bean.ShopDO;import net.sf.json.JSONObject; public class MongoTemplateTest { public static MongoTemplate mongoTemplate = getMongoTemplate(); public static void main(String[] args) { System.out.println(mongoTemplate.getCollectionNames()); } public static MongoTemplate getMongoTemplate(){ String host = "192.168.16.121"; int port = 27017; String databaseName = "test"; String username = "root"; String password = "123456Ab"; //ServerAddress(host,port)兩個參數分別為 IP地址 端口號 ServerAddress serverAddress = new ServerAddress(host,port); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential(username,source,password)三個參數分別為 用戶名 數據庫名稱 密碼 MongoCredential credential = MongoCredential.createScramSha1Credential(username, databaseName, password.toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //通過連接認證獲取MongoDB連接 MongoClient mongoClient = new MongoClient(addrs,credentials); MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, databaseName); MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory); return mongoTemplate; } /** * 插入數據 */ @Test public void save(){ ShopDO shop1 = new ShopDO(100L,"菜鳥教程"); ShopDO shop2 = new ShopDO(101L,"有道筆記"); mongoTemplate.save(shop1,"col"); mongoTemplate.save(shop2,"col"); System.out.println("mongoDB插入數據成功,集合為col,文檔為:"+mongoTemplate.getCollection("col")); } @Test public void save1(){ Book book = new Book(22L,"英語","32.5"); mongoTemplate.save(book,"col"); } @Test public void save2(){ Good good = new Good(new HashMap<String,String>(){{put("id","1");put("name","動物");}}); mongoTemplate.save(good,"col"); } @Test public void save3(){ mongoTemplate.save(JSONObject.fromObject("{\"這樣\":\"we\",\"好吧\":\"hai\"}"),"col"); System.out.println("mongoDB插入數據成功,集合為col,文檔為:"+mongoTemplate.getCollection("col")); } /** * 查詢所有 */ @Test public void findAll(){ List<ShopDO> list = mongoTemplate.findAll(ShopDO.class,"col"); System.out.println("mongoDB查詢數據成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 單條件查詢 */ @Test public void simpleQuery(){ Query query = Query.query(Criteria.where("no").is(100L)); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB按條件ID查詢數據成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 多條件查詢 */ @Test public void muchQuery(){ Criteria criteria = new Criteria(); //or是條件或查詢,and是條件與查詢 criteria.orOperator( Criteria.where("no").is(100), Criteria.where("name").is("菜鳥教程")); Query query = new Query(criteria); //組合查詢放入query Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC,"no")); //結果集進行排序 query.with(sort); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB組合查詢數據成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 分頁查詢 */ @Test public void LimitQuery(){ Query query = new Query(); query.skip(1).limit(3); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB分頁查詢下標為1開始總共3行數據,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** * 模糊查詢 */ @Test public void LikeQuery(){ Query query = new Query(Criteria.where("name").regex("菜鳥")); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB查詢名稱叫菜鳥的數據成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } Update update = new Update(); update.set("name","菜鳥教程old"); WriteResult wr = mongoTemplate.updateMulti(query,update,"col"); System.out.println("mongoDB更新數據成功,集合為col,行數為:" + wr.getN()); } /** * 更新 */ @Test public void update(){ Query query = new Query(Criteria.where("no").is(100)); List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB查詢no為100的數據成功,集合為col,文檔為:"); for (ShopDO shopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } Update update = new Update(); update.set("name","菜鳥教程new"); WriteResult wr = mongoTemplate.updateFirst(query,update,"col"); System.out.println("mongoDB更新數據成功,集合為col,行數為:" + wr.getN()); } /** * 刪除 */ @Test public void delete(){ Query query = new Query(Criteria.where("no").is(1)); WriteResult result = mongoTemplate.remove(query, "col"); System.out.println("mongoDB刪除數據成功,集合為col,行數為:" + result.getN() + "刪除的ID為"+result.getUpsertedId()); }}
關于Java中怎么獲取MongoDB連接就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。