使用java驱动链接MongoDB是一件非常简单的事情,简单的引用,简单的做增删改查。在使用完java驱动后我才发现spring 对MongoDB 的封装还不如官方自身提供出来的东西好用,下面简单的展示一下使用。
1.使用maven引入jar包
- <dependency>
- <groupId>org.mongodb</groupId>
- <artifactId>mongodb-driver-sync</artifactId>
- <version>3.8.0-beta3</version>
- </dependency>
2.创建一个访问客户端
- MongoClient client = MongoClients.create(“mongodb://10.201.76.94:27017”);
3.获取集合数量
- public long count() {
- MongoClient client = this.getClient();
- MongoCollection<Document> collections= client.getDatabase("mongodb_db_name").getCollection("mongodb_collection_name");
- return collections.count();
- }
4.查询集合
- public List<Document> find(Document params,Bson sort,int skip,int limit) {
- MongoClient client = this.getClient();
- MongoCollection<Document> collections= client.getDatabase("mongodb_db_name").getCollection("mongodb_collection_name");
- List<Document> list = new ArrayList<Document>(Integer.valueOf(config.getPro("sync_limit")));
- collections.find(params).sort(sort).skip(skip).limit(limit).forEach(new Block<Document>() {
- @Override
- public void apply(Document document) {
- list.add(document);
- }
- });
- return list;
- }
(编辑:西安站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|