Java中获取MongoDB连接的方法详解
首先是所需jar包,Maven中的配置如下:
org.mongodb mongodb-driver 3.4.1 org.mongodb bson 3.4.1 org.springframework.data spring-data-mongodb 1.7.0.RELEASE org.mongodb mongo-java-driver 3.9.1
获取连接的代码如下(本中用的是模板类):
Listaddrs=newArrayList (); addrs.add(newServerAddress(dataSource.getSourceIp(),Integer.valueOf(dataSource.getSourcePort()))); List credentials=newArrayList (); credentials.add(MongoCredential.createScramSha1Credential(dataSource.getUsername(),dataSource.getSourceName(),dataSource.getPassword().toCharArray())); MongoClientmongoClient=newMongoClient(addrs,credentials); MongoDbFactorymongoDbFactory=newSimpleMongoDbFactory(mongoClient,dataSource.getSourceName()); MongoTemplatemongoTemplate=newMongoTemplate(mongoDbFactory); mongoTemplate.getCollectionNames();
或者用如下方式获取:
ServerAddressserverAddress=newServerAddress("192.168.16.121",27017); Listaddrs=newArrayList (); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三个参数分别为用户名数据库名称密码 MongoCredentialcredential=MongoCredential.createScramSha1Credential("root","admin","123456Ab".toCharArray()); List credentials=newArrayList (); credentials.add(credential); //通过连接认证获取MongoDB连接 MongoClientmongoClient=newMongoClient(addrs,credentials); //连接到数据库 MongoDatabasemongoDatabase=mongoClient.getDatabase("admin"); mongoDatabase.getCollection("test").find().iterator(); //关闭数据库连接 mongoClient.close();
附带简单增删改查的例子:
packagetest; importjava.util.ArrayList; importjava.util.HashMap; importjava.util.List; importorg.junit.Test; importorg.springframework.data.domain.Sort; importorg.springframework.data.mongodb.MongoDbFactory; importorg.springframework.data.mongodb.core.MongoTemplate; importorg.springframework.data.mongodb.core.SimpleMongoDbFactory; importorg.springframework.data.mongodb.core.query.Criteria; importorg.springframework.data.mongodb.core.query.Query; importorg.springframework.data.mongodb.core.query.Update; importcom.mongodb.MongoClient; importcom.mongodb.MongoCredential; importcom.mongodb.ServerAddress; importcom.mongodb.WriteResult; importbean.Book; importbean.Good; importbean.ShopDO; importnet.sf.json.JSONObject; publicclassMongoTemplateTest{ publicstaticMongoTemplatemongoTemplate=getMongoTemplate(); publicstaticvoidmain(String[]args){ System.out.println(mongoTemplate.getCollectionNames()); } publicstaticMongoTemplategetMongoTemplate(){ Stringhost="192.168.16.121"; intport=27017; StringdatabaseName="test"; Stringusername="root"; Stringpassword="123456Ab"; //ServerAddress(host,port)两个参数分别为IP地址端口号 ServerAddressserverAddress=newServerAddress(host,port); Listaddrs=newArrayList (); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential(username,source,password)三个参数分别为用户名数据库名称密码 MongoCredentialcredential=MongoCredential.createScramSha1Credential(username,databaseName,password.toCharArray()); List credentials=newArrayList (); credentials.add(credential); //通过连接认证获取MongoDB连接 MongoClientmongoClient=newMongoClient(addrs,credentials); MongoDbFactorymongoDbFactory=newSimpleMongoDbFactory(mongoClient,databaseName); MongoTemplatemongoTemplate=newMongoTemplate(mongoDbFactory); returnmongoTemplate; } /** *插入数据 */ @Test publicvoidsave(){ ShopDOshop1=newShopDO(100L,"菜鸟教程"); ShopDOshop2=newShopDO(101L,"有道笔记"); mongoTemplate.save(shop1,"col"); mongoTemplate.save(shop2,"col"); System.out.println("mongoDB插入数据成功,集合为col,文档为:"+mongoTemplate.getCollection("col")); } @Test publicvoidsave1(){ Bookbook=newBook(22L,"英语","32.5"); mongoTemplate.save(book,"col"); } @Test publicvoidsave2(){ Goodgood=newGood(newHashMap (){{put("id","1");put("name","动物");}}); mongoTemplate.save(good,"col"); } @Test publicvoidsave3(){ mongoTemplate.save(JSONObject.fromObject("{\"这样\":\"we\",\"好吧\":\"hai\"}"),"col"); System.out.println("mongoDB插入数据成功,集合为col,文档为:"+mongoTemplate.getCollection("col")); } /** *查询所有 */ @Test publicvoidfindAll(){ List list=mongoTemplate.findAll(ShopDO.class,"col"); System.out.println("mongoDB查询数据成功,集合为col,文档为:"); for(ShopDOshopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** *单条件查询 */ @Test publicvoidsimpleQuery(){ Queryquery=Query.query(Criteria.where("no").is(100L)); List list=mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB按条件ID查询数据成功,集合为col,文档为:"); for(ShopDOshopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** *多条件查询 */ @Test publicvoidmuchQuery(){ Criteriacriteria=newCriteria(); //or是条件或查询,and是条件与查询 criteria.orOperator( Criteria.where("no").is(100), Criteria.where("name").is("菜鸟教程")); Queryquery=newQuery(criteria);//组合查询放入query Sortsort=newSort(newSort.Order(Sort.Direction.DESC,"no"));//结果集进行排序 query.with(sort); List list=mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB组合查询数据成功,集合为col,文档为:"); for(ShopDOshopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** *分页查询 */ @Test publicvoidLimitQuery(){ Queryquery=newQuery(); query.skip(1).limit(3); List list=mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB分页查询下标为1开始总共3行数据,集合为col,文档为:"); for(ShopDOshopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } } /** *模糊查询 */ @Test publicvoidLikeQuery(){ Queryquery=newQuery(Criteria.where("name").regex("菜鸟")); List list=mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB查询名称叫菜鸟的数据成功,集合为col,文档为:"); for(ShopDOshopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } Updateupdate=newUpdate(); update.set("name","菜鸟教程old"); WriteResultwr=mongoTemplate.updateMulti(query,update,"col"); System.out.println("mongoDB更新数据成功,集合为col,行数为:"+wr.getN()); } /** *更新 */ @Test publicvoidupdate(){ Queryquery=newQuery(Criteria.where("no").is(100)); List list=mongoTemplate.find(query,ShopDO.class,"col"); System.out.println("mongoDB查询no为100的数据成功,集合为col,文档为:"); for(ShopDOshopDO:list){ System.out.println(shopDO.getNo()+"/"+shopDO.getName()); } Updateupdate=newUpdate(); update.set("name","菜鸟教程new"); WriteResultwr=mongoTemplate.updateFirst(query,update,"col"); System.out.println("mongoDB更新数据成功,集合为col,行数为:"+wr.getN()); } /** *删除 */ @Test publicvoiddelete(){ Queryquery=newQuery(Criteria.where("no").is(1)); WriteResultresult=mongoTemplate.remove(query,"col"); System.out.println("mongoDB删除数据成功,集合为col,行数为:"+result.getN()+"删除的ID为"+result.getUpsertedId()); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。