如何在mongodb中使用driver?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

1 环境准备

创建工程,并添加以下依赖:

<dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver</artifactId><version>3.10.1</version></dependency>

2 使用mongodb-driver

2.1 查询所有

@Testpublicvoidtest1(){//创建连接MongoClientclient=newMongoClient("192.168.200.128");//打开数据库MongoDatabasecommentdb=client.getDatabase("commentdb");//获取集合MongoCollection<Document>comment=commentdb.getCollection("comment");//查询FindIterable<Document>documents=comment.find();//查询记录获取文档集合for(Documentdocument:documents){System.out.println("_id:"+document.get("_id"));System.out.println("内容:"+document.get("content"));System.out.println("用户ID:"+document.get("userid"));System.out.println("点赞数:"+document.get("thumbup"));}//关闭连接client.close();}}

2.2 根据_id查询

每次使用都要用到MongoCollection,进行抽取:

privateMongoClientclient;privateMongoCollection<Document>comment;@Beforepublicvoidinit(){//创建连接client=newMongoClient("192.168.200.128");//打开数据库MongoDatabasecommentdb=client.getDatabase("commentdb");//获取集合comment=commentdb.getCollection("comment");}@Afterpublicvoidafter(){client.close();}@Testpublicvoidtest2(){//查询FindIterable<Document>documents=comment.find(newBasicDBObject("_id","1"));//查询记录获取文档集合for(Documentdocument:documents){System.out.println("_id:"+document.get("_id"));System.out.println("内容:"+document.get("content"));System.out.println("用户ID:"+document.get("userid"));System.out.println("点赞数:"+document.get("thumbup"));}}

2.3 新增

@Testpublicvoidtest3(){Map<String,Object>map=newHashMap();map.put("_id","6");map.put("content","很棒!");map.put("userid","9999");map.put("thumbup",123);Documentdocument=newDocument(map);comment.insertOne(document);}

2.4 修改

@Testpublicvoidtest4(){//修改的条件Bsonfilter=newBasicDBObject("_id","6");//修改的数据Bsonupdate=newBasicDBObject("$set",newDocument("userid","8888"));comment.updateOne(filter,update);}

2.5 删除

@Testpublicvoidtest5(){//删除的条件Bsonfilter=newBasicDBObject("_id","6");comment.deleteOne(filter);}

MongoDB优势与劣势

优势:

1、在适量级的内存的MongoDB的性能是非常迅速的,它将热数据存储在物理内存中,使得热数据的读写变得十分快。
2、MongoDB的高可用和集群架构拥有十分高的扩展性。
3、在副本集中,当主库遇到问题,无法继续提供服务的时候,副本集将选举一个新的主库继续提供服务。
4、MongoDB的Bson和JSon格式的数据十分适合文档格式的存储与查询。

劣势:

1、 不支持事务操作。MongoDB本身没有自带事务机制,若需要在MongoDB中实现事务机制,需通过一个额外的表,从逻辑上自行实现事务。
2、 应用经验少,由于NoSQL兴起时间短,应用经验相比关系型数据库较少。
3、MongoDB占用空间过大。

关于如何在mongodb中使用driver问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。