Java操作mongodb增删改查的基本操作

目录

前言

一、MongoDB是 什么?

二、JAVA链接数据库

        2.1、引入jar包

         2.2、 获取链接对象

          2.3、关闭链接

三、MongoDB在Java中的CRUD

        3.1. 新增数据

        3.2删除数据

        3.3、修改数据

        3.4查询数据


前言

          非关系型数据库,又称NoSQL(不仅仅是sql),NoSQL主要是指非关系型、分布式、不提供ACID (数据库事务处理的四个基本要素)的数据库设计模式。我们都知道,MySQL是关系型数据库,它是以表的形式存在数据库中每一行都是一条记录,而最近学习的mongoDB属于非关系型数据库,它主要以集合的形式保存数据


一、MongoDB是 什么?

        MongoDB是一种面向文档的数据库管理系统。用C++等语言撰写而成,它支持的数据结构非常松散,是类似 json 的 bson 格式,因此可以存储比较复杂的数据类型。Mongo 最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。在Java平常的使用过程并不是在库中直接使用,而是通过三方jar包进行链接,所以在简单介绍一下Java链接数据库mongoDB,以及其CRUD。

二、JAVA链接数据库

        2.1、引入jar包

        

         2.2、 获取链接对象

                     参数填入服务器地址和端口号

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

          2.3、关闭链接

mc.close();

三、MongoDB在Java中的CRUD

        3.1. 新增数据

  • 在前面获取链接后,我们需要:
  • 再获取数据库,明确需要操作的数据库
  • 再获取数据库中的集合对象,明确需要操作的集合对象,它会返回一个Document泛型的MongoCollection对象
  • 创建JavaBean的Student
  • 将数据用put的方式新增进集合
  • 集合提供一个insertMany()的方法来新增数据库中的元素。

public class TianJia {

	public static void main(String[] args) {
		
		// 连接对象
		MongoClient mc = new MongoClient("localhost", 27017);
		
		// 库对象
		MongoDatabase db = mc.getDatabase("school");
		
		// 集合对象
		MongoCollection<Document> collection = db.getCollection("Teacher");
		
		// 新增
		Document document1 = new Document();
		document1.put("name", "张三");
		document1.put("age", 18);
		document1.put("birthday", new Date());
		document1.put("sex", "男");
		Document document2 = new Document();
		document2.put("name", "张三");
		document2.put("age", 18);
		document2.put("birthday", new Date());
		document2.put("sex", "男");
		Document document3 = new Document();
		document3.put("name", "张三");
		document3.put("age", 18);
		document3.put("birthday", new Date());
		document3.put("sex", "男");
		Document document4 = new Document();
		document4.put("name", "张三");
		document4.put("age", 18);
		document4.put("birthday", new Date());
		document4.put("sex", "男");
		
		List<Document> listdoc = new ArrayList<Document>();
		listdoc.add(document1);
		listdoc.add(document2);
		listdoc.add(document3);
		listdoc.add(document4);
		
		// 添加一条数据
//		collection.insertOne(document);
		// 一次添加多条数据
		collection.insertMany(listdoc);
				
		mc.close();

	}
}

        3.2删除数据

        

  • 在前面获取链接后,我们需要:
  • 再获取数据库,明确需要操作的数据库
  • 再获取数据库中的集合对象,明确需要操作的集合对象,它会返回一个Document泛型的MongoCollection对象
  • 判断age存在;Bson exists = Filters.exists("age", false);
  • 执行删除操作

代码如下(示例):

public class DeleteData {
	public static void main(String[] args) {
		
		// 连接对象
		MongoClient mc = new MongoClient("localhost", 27017);
		
		// 库对象
		MongoDatabase db = mc.getDatabase("myschool");
		
		// 集合对象
		MongoCollection<Document> collection = db.getCollection("student");
		
//		Bson gt = Filters.gt("age", 100);
//		Bson exists = Filters.exists("age");
		Bson exists = Filters.exists("age", false);
		//删除一条数据,删除name=张三的 遇到的第一条数据
		DeleteResult deleteOne = collection.deleteOne(new Document("name","张三"));
        //删除name=张三的所有数据
		DeleteResult deleteMany = collection.deleteMany(new Document("name","张三"));
       
		System.out.println(deleteMany);
		
		mc.close();
		
		
	}
}

        3.3、修改数据

需要注意的是删除的代码格式有一点点 的区别,需要加上$set

collection.updateOne(
              eq, new Document("$set",new Document("age", 20)),
                  new UpdateOptions().upsert(true));

                new UpdateOptions().upsert(true)

                返回修改信息

public class UpdateDemo {

	public static void main(String[] args) {
		
		// 连接对象
		MongoClient mc = new MongoClient("localhost", 27017);
		
		// 库对象
		MongoDatabase db = mc.getDatabase("myschool");
		
		// 集合对象
		MongoCollection<Document> collection = db.getCollection("student");
		
		
		Bson eq = Filters.eq("name", "任龙");
		
		// 多条件的
		Bson and = Filters.and(Filters.gte("age", 20),Filters.lte("age", 30));
		

		UpdateResult updateMany = collection.updateMany(
				and, new Document("$inc",new Document("age",100)));
		


		UpdateResult updateOne = collection.updateOne(
				eq, new Document("$set",new Document("age", 20)),
					new UpdateOptions().upsert(true));
		
		
		System.out.println(updateMany);
		
		
		
		mc.close();

	}
}

        3.4查询数据

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

        找到name有张的数据

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

        倒序排序

        循环遍历

public class SelectDemo {

	public static void main(String[] args) {
		
		
		Gson gson = new GsonBuilder().create();
		
		// 连接对象
		MongoClient mc = new MongoClient("localhost", 27017);
		
		// 库对象 -- 获取  创建
		MongoDatabase db = mc.getDatabase("myschool");
		
		// 集合对象 -- 获取 创建
		MongoCollection<Document> collection = db.getCollection("student");
		
		// 添加条件
		Bson eq = Filters.regex("name", "张");
		Document document = new Document("birthday",-1);
		
		FindIterable<Document> find = collection.find(eq).sort(document);

		
		List<Student>  slist = new ArrayList<Student>();
		
		MongoCursor<Document> iterator = find.iterator();
		
		
		while(iterator.hasNext()) {
			Student s =  new Student();
			
			Document next = iterator.next();
			s.setSname(next.getString("name"));
			s.setSsex(next.getString("sex"));
			s.setSid(next.getInteger("sid"));
			
			// 参数1 Json 字符串
			// 参数2 需要的对象的类型
			

			
			slist.add(s);
		}
		
		
		for(Student ss : slist){
			System.out.println(ss);
		}

		mc.close();

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值