Java连接MongoDB的常用方法详解

目录
  • 一、Java链接MongoDB
  • 二、查看库,查看集合
  • 三、Java对MongoDB增删改查
    • 1. 添加数据
    • 2. 删除数据
    • 3. 修改数据
    • 4. 查询数据

一、Java链接MongoDB

1. 导入Mongo驱动包

2. 获取Mongo链接对象

MongoClient mc = new MongoClient("localhost",27017);

3. 关闭链接

mc.close();

二、查看库,查看集合

1. 获取库对象

MongoDatabase db = mc.getDatabase("myschool");

2. 获取库中表的集合

MongoIterable<String> listCollectionNames = db.listCollectionNames();

MongoCursor<String> iterator = listCollectionNames.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }

三、Java对MongoDB增删改查

1. 添加数据

a. 添加一条数据

//创建对象
Student s = new Student();
s.setSid(1);
s.setSname("王俊凯");
s.setBirthday(new Date());
s.setSsex("男");
s.setClassid(2);

//将数据转换为json格式
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String json = gson.toJson(s);

//获取集合对象
MongoCollection<Document> collection = db.getCollection("student");

//添加一条数据,将json格式转换为document对象
collection.insertOne(Document.parse(json));

b. 添加多条数据

//存入数据
List<Document> dlist=new ArrayList<Document>();

for(int i=0; i<3; i++){
    Student s = new Student();
    s.setSid(Integer.toString(i+1));
    s.setSname("王源");
    s.setBirthday(new Date());
    s.setSsex("男");
    s.setClassid(1);
    //将数据转换为json格式
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    String json = gson.toJson(s);
    dlist.add(Document.parse(json));
}

//获取集合对象
MongoCollection<Document> collection = db.getCollection("student");

//添加多条数据
collection.insertMany(dlist);

2. 删除数据

a. 删除一条数据

//获取集合对象
MongoCollection<Document> collection = db.getCollection("student");

Student s = new Student();
s.setSid(1);

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Bson bson = Document.parse(gson.toJson(s));

DeleteResult deleteOne = collection.deleteOne(bson);

b. 删除多条数据

//获取集合对象
MongoCollection<Document> collection = db.getCollection("student");

Student s = new Student();
s.setSname("王源");

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Bson bson = Document.parse(gson.toJson(s));

DeleteResult deleteMany = collection.deleteMany(bson);

3. 修改数据

a. 修改一条数据

MongoCollection<Document> collection = db.getCollection("student");

//一个条件对象
Bson eq = Filters.eq("sname","易烊千玺");

//要修改的数据
Document doc = new Document();
doc.put("$set", new Document("age",22));
UpdateResult  updateone = collection.updateOne(eq, doc);
System.out.println(updateone);

b. 修改多条数据

MongoCollection<Document> collection = db.getCollection("student");

//多条件
Bson bson = Filters.and(Filters.gte("age", 20),Filters.lte("age", 40));

//要修改的数据
Document doc = new Document();
doc.put("$set", new Document("sex","男"));
UpdateResult updateMany = collection.updateMany(bson, doc);
System.out.println(updateMany);

4. 查询数据

a. 全查

MongoCollection<Document> collection = db.getCollection("student");

FindIterable<Document> findAll = collection.find();

MongoCursor<Document> iterator = findAll.iterator();

while(iterator.hasNext()){
   System.out.println(iterator.next());
}

b. 带条件查询

MongoCollection<Document> collection = db.getCollection("student");

//一个条件对象
Bson eq = Filters.eq("sname","易烊千玺");

FindIterable<Document> findOne = collection.find(eq);

MongoCursor<Document> iterator = findOne.iterator();

while(iterator.hasNext()){
   System.out.println(iterator.next());
}

c. 模糊查询

MongoCollection<Document> collection = db.getCollection("student");

//使用正则表达式进行模糊查找
Bson eq = Filters.regex("sname","易");

FindIterable<Document> find = collection.find(eq);

MongoCursor<Document> iterator = find.iterator();

while(iterator.hasNext()){
   System.out.println(iterator.next());
}

d. 分页查询

MongoCollection<Document> collection = db.getCollection("student");

//分页查询
FindIterable<Document> find = collection.find().skip(2).limit(3);

MongoCursor<Document> iterator = find.iterator();

while(iterator.hasNext()){
   System.out.println(iterator.next());
}

e. 排序查询

MongoCollection<Document> collection = db.getCollection("student");

//排序查询  1升序   -1降序
Bson bson = new Document("sid",1);
FindIterable<Document> find = collection.find().sort(bson);

MongoCursor<Document> iterator = find.iterator();

while(iterator.hasNext()){
   System.out.println(iterator.next());
}

到此这篇关于Java连接MongoDB的常用方法详解的文章就介绍到这了,更多相关Java连接MongoDB内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Java中获取MongoDB连接的方法详解

    首先是所需jar包,Maven中的配置如下: <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mongodb</groupId>

  • Java的idea连接mongodb数据库的详细教程

    最近有一个java实验,要求用java使用数据库,于是本人新手小白,在idea上卡了好半天 希望看到这个博客的人能解决问题,跳过一些坑 首先,我这里用的是 mongodb 数据库(ps:node.js下mongo太好用了,就没有mysql) 1,用idea创建一个maven工程 由于不牵扯太多功能,直接 next 就行了, 很无奈,创建完就直接报错了 找不到 maven 相关的插件 Cannot resolve plugin org.apache.maven.plugins:maven-comp

  • java实现mongodb的数据库连接池

    MongoDB是介于关系数据库和非关系数据库之间的一种产品,文件的存储格式为BSON(一种JSON的扩展),这里就主要介绍Java通过使用mongo-2.7.3.jar包实现mongodb连接池,具体的java代码实现如下: 数据库连接池配置参数: /** *@Description: mongo连接池配置文件 */ package cn.lulei.mongo.pool; public class MongoConfig { private static String userName;//用

  • Java连接MongoDB进行增删改查的操作

    Java连接MongoDB进行增删改查的操作 1.创建数据库的连接,进行增删改查 (分别为接口和实现类) package com.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mo

  • java连接mongoDB并进行增删改查操作实例详解

    本文实例讲述了java连接mongoDB并进行增删改查操作.分享给大家供大家参考,具体如下: 1.安装 MongoDB JDBC驱动程序 在java中使用mongoDB之前,首先需要拥有java连接mongoDB的第三方驱动包(jar包) 1)maven项目可通过在pom.xml中添加依赖 <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-ja

  • java连接Mongodb实现增删改查

    本文实例为大家分享了java连接Mongodb实现增删改查的具体代码,供大家参考,具体内容如下 1.创建maven项目 <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.4.1</version> </dependency> 2.编写代码 1.查询所有 package co

  • Java连接MongoDB的常用方法详解

    目录 一.Java链接MongoDB 二.查看库,查看集合 三.Java对MongoDB增删改查 1. 添加数据 2. 删除数据 3. 修改数据 4. 查询数据 一.Java链接MongoDB 1. 导入Mongo驱动包 2. 获取Mongo链接对象 MongoClient mc = new MongoClient("localhost",27017); 3. 关闭链接 mc.close(); 二.查看库,查看集合 1. 获取库对象 MongoDatabase db = mc.getD

  • Java操作MongoDB数据库方法详解

    Java与mongodb的连接 1. 连单台mongodb Mongo mg = new Mongo();//默认连本机127.0.0.1 端口为27017 Mongo mg = new Mongo(ip);//可以指定ip 端口默认为27017 Mongo mg = new Mongo(ip,port);//也可以指定ip及端口 2. 连双台mongodb //ip为主机ip地址,port为端口号,dataBaseName相当于数据库名 DBAddress left = new DBAddre

  • java连接mysql底层封装详解

    本文实例为大家分享了java连接mysql底层封装代码,供大家参考,具体内容如下 连接数据库 package com.dao.db; import java.sql.Connection; import java.sql.SQLException; /** * 数据库连接层MYSQL * @author Administrator * */ public class DBConnection { /** * 连接数据库 * @return */ public static Connection

  • Java jpa外连接查询join案例详解

    1.IndexTagController.java @GetMapping("/tags/{id}") public String types(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable, @PathVariable long id, Model model, HttpSession session){ //找到所有

  • Java Map接口概述和常用方法详解

    目录 概述 Map常用子类 Map接口中的常用方法 Map集合遍历键找值方式 Entry键值对对象 Map集合遍历键值对方式 概述 现实生活中,我们常会看到这样的一种集合:IP地址与主机名,身份证号与个人,系统用户名与系统用户对象等,这种一一对应的关系,就叫做映射.Java提供了专门的集合类用来存放这种对象关系的对象,即java.util.Map接口. 我们通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它们存储数据的形式不同,如下图. Collection中的

  • Java Http请求方式之RestTemplate常用方法详解

    目录 引言 常见用法 简单Get\Post请求 Post提交常规表单 Post上传文件 配置项 请求添加Cookie\Header 配置请求工厂 超时.代理 配置拦截器.转换器,错误处理 错误重试(额外) SSL请求 基于RestTemplate一些工具 钉钉机器人通知 总结 引言 在开发中有时候经常需要一些Http请求,请求数据,下载内容,也有一些简单的分布式应用直接使用Http请求作为跨应用的交互协议. 在Java中有不同的Http请求方式,主要就是HttpURLConnection或者Ap

  • 浅谈JAVA中输入输出流实例详解

    java语言的输入输出功能是十分强大而灵活的,美中不足的是看上去输入输出的代码并不是很简洁,因为你往往需要包装许多不同的对象.在Java类库中,IO部分的内容是很庞大的,因为它涉及的领域很广泛:标准输入输出,文件的操作,网络上的数据流,字符串流,对象流,zip文件流....本文的目的是为大家介绍JAVA中输入输出流实例详解. 流的层次结构 定义:        java将读取数据对象成为输入流,能向其写入的对象叫输出流.结构图如下: 1.输入输出: 输入/输出(Input/Output)是指对某

  • java基面试础知识详解

    面向对象的三大特性 1)封装 就是把同一类事物的属性和方法归到同一个类中,方便使用 防止该类的代码和数据被外部类定义的代码随意访问 要访问该类的数据和代码必须通过严格的方法控制 封装的主要功能在于我们能修改自己的实现代码,而不用修改哪些调用程序的代码片段. 优点:减少耦合,类内部自由修改,可以对类成员变量进行更精确的控制,隐藏信息.实现细节. 最佳实践: 为了实现良好的封装,通常将类的成员变量声明为private ,通过public的set和get方法完成对属性的操作 2)继承 继承就是子类继承

  • java中stringBuilder的用法详解

    String对象是不可改变的.每次使用System.String类中的方法之一时,都要在内存中创建一个新的字符串对象,这就需要为该新对象分配新的空间.在需要对字符串执行重复修改的情况下,与创建新的String对象相关的系统开销可能会非常昂贵.如果要修改字符串而不创建新的对象,则可以使用System.Text.StringBuilder类.例如,当在一个循环中将许多字符串连接在一起时,使用StringBuilder类可以提升性能. 通过用一个重载的构造函数方法初始化变量,可以创建StringBui

随机推荐