目录

一、java操作MongoDB数据库的基本步骤

二、操作MongoDB数据库—— insert数据

三、操作MongoDB数据库—— delete数据

四、操作MongoDB数据库—— update数据

五、操作MongoDB数据库—— find数据

六、全部代码展示


一、java操作MongoDB数据库的基本步骤

1、在项目中引入MongoDB驱动包

2、在MongoDB数据库中创建myschool集合。【db.createCollection("student");】

        

 

3、创建类,执行以下步骤

        3.1.获取连接对象:【MongoClient mc = new MongoClient("localhost",27017);】

        3.2.获取并创建库对象:【MongoDatabase db = mc.getDatabase("myschool");】

        3. 3.获取并创建集合对象:【MongoCollection<Document> collection =                 db.getCollection("student");】

        3. 4.关闭mc.close();

对于后续方便操作我们可以将其封装起来【写成一个MongoDBUtil.java文件】

package com.ape.dao;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

public class MongoUtil {

	private static MongoClient mongoClient;
	
	public static MongoDatabase getDB() {
		 MongoClient mongoClient = new MongoClient("localhost",27017);
		 MongoDatabase database = mongoClient.getDatabase("bookComm");
		 return database;
	}
	
	public static void closeMongo() {
		if(mongoClient != null) {
			mongoClient.close();
		}
	}
}

二、操作MongoDB数据库—— insert数据

        语法:collection.insertOne(document);//一次添加一条数据

                   collection.insertMany(list);//一次添加多条记录

        具体实例如下

                1.创建学生实体类 

package com.shang.Bean;

import java.util.Date;

public class Student {
	private Date birthday;
	private String  name;
	private String sex;
	private int age;
	
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date date) {
		this.birthday = date;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(Date birthday, String name, String sex, int age) {
		super();
		this.birthday = birthday;
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [birthday=" + birthday + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
	}

}

        2.创建测试类

@SuppressWarnings("resource")
	public static void main(String[] args) {
		//1.获取MongoDB的连接对象
		MongoClient mc = new MongoClient("localhost",27017);
		System.out.println(mc);
		//查看数据库中所有的库 数据库连接对象.listDatabaseNames();得到一个iterator,遍历
		MongoIterable<String> listDatabaseNames = mc.listDatabaseNames();
		MongoCursor<String> iterator = listDatabaseNames.iterator();
		while(iterator.hasNext()) {
			String next = iterator.next();
			System.out.println(next);
		}
		
		//2.获得库对象: 数据库连接对象.getDatabase("数据库名")
		MongoDatabase db = mc.getDatabase("myschool");
		System.out.println(db);
		
		
		//取到库中的集合 :库对象.listCollectionNames(); 遍历
		MongoIterable<String> listCollectionNames = db.listCollectionNames();
		for(String str:listCollectionNames) {
			System.out.println(str);
		}
		
		//3.获取对象
		MongoCollection<Document> collection = db.getCollection("student");
		System.out.println();

		//新增
		Document document = new Document();
		document.put("name", "张瑜");
		document.put("birthday", "2022-9-13");
		document.put("sex", "男");
		document.put("age", "18");
		//添加一条数据,没有返回值
		collection.insertOne(document);

        //添加多条数据
        Document document1 = new Document();
		document1.put("name", "张瑜");
		document1.put("birthday", "2022-9-13");
		document1.put("sex", "男");
		document1.put("age", "18");
		Document document2 = new Document();
		document2.put("name", "婳樱");
		document2.put("birthday", "2022-9-13");
		document2.put("sex", "女");
		document2.put("age", "18");
		Document document3 = new Document();
		document3.put("name", "王黎");
		document3.put("birthday", "2022-9-13");
		document3.put("sex", "男");
		document3.put("age", "18");
		Document document4 = new Document();
		document4.put("name", "张瑜");
		document4.put("birthday", "2022-9-13");
		document4.put("sex", "男");
		document4.put("age", "18");
		Document document5 = new Document();
		document5.put("name", "张瑜");
		document5.put("birthday", "2022-9-13");
		document5.put("sex", "男");
		document5.put("age", "18");
		
		ArrayList<Document> list =new ArrayList<>();
		list.add(document1);
		list.add(document2);
		list.add(document3);
		list.add(document4);
		list.add(document5);
		collection.insertMany(list);

三、操作MongoDB数据库—— delete数据

        语法: collection.deleteOne(new Document("name","张瑜"));//一次删除一条数据

                   collection.updateMany(eq, new Document("$set",new Document("age",20)));;//一次删除多条记录

        具体实例如下

        Bson gt = Filters.gt("age", 100);
		Bson exists = Filters.exists("sex");
		Bson exists2 = Filters.exists("sex", false);

        //一次删除一条数据
		DeleteResult deleteOne = collection.deleteOne(new Document("name","张瑜"));
		System.out.println(deleteOne);
		
		DeleteResult deleteOne2 = collection.deleteMany(gt);
		System.out.println(deleteOne2);

        //一次删除多条数据
		DeleteResult deleteMany = collection.deleteMany(exists2);
		System.out.println(deleteMany);

关于过滤器,bson的解释

        学习过滤器Filters:该过滤器为所有的MongoDB的查询操作静态工厂方法。每个方法返回BSON类型,又可以传递给期望查询锅过滤器的任何一个方法的实例。【Bson eq = Filters.eq("name","张瑜");

四、操作MongoDB数据库—— update数据

        语法: collection.updateOne(eq, new Document("$set",new Document("age",21)));//一次更新一条数据

                   collection.updateMany(eq, new Document("$set",new Document("age",20)));;//一次更新多条记录

        具体实例如下

        
        //修改[学习过滤器Filters]
		Bson eq = Filters.eq("name","张瑜");
        //一次更新一条数据
		UpdateResult updateOne = collection.updateOne(eq, new Document("$set",new Document("age",21)));
		System.out.println(updateOne);
		//输出结果matchedCount=1, modifiedCount=1, upsertedId=null
		
        //一次更新多条数据
		UpdateResult updateMany = collection.updateMany(eq, new Document("$set",new Document("age",20)));
		System.out.println(updateMany);
		//输出结果:matchedCount=7, modifiedCount=1, upsertedId=null
		
		//使upsertid有值【matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{value=631fe6fdcdfd423e2a54d588}】
		UpdateResult updateMany1 = collection.updateMany(eq, new Document("$set",new Document("age",20)),new UpdateOptions().upsert(true));
		System.out.println(updateMany1);


        //Filters利用and/or方法将多个条件变成一个Bson格式作为条件,年龄大于20,小于等于30的学                    生性别改为保密
		Bson eq1 = Filters.gte("age",20);
		Bson lte = Filters.lte("age", 30);
		Bson and = Filters.and(eq1,lte);
		UpdateResult updateMany2 = collection.updateMany(and, new Document("$set",new Document("sex","保密")));
		System.out.println(updateMany2);
		
		//Inc给文件的字段加上100
		UpdateResult updateMany3 = collection.updateMany(and, new Document("$inc",new Document("age",100)));
		System.out.println(updateMany3);

关于update输出结果的解释【三个输出值的解释】

        1、matchedCount 找到的符合条件的记录条数 ,

        2、modifiedCount=1 更新的记录条数,

        3、upsertedId 如果更新的记录不存在,就会新建一条数据,返回的是新建数据的id号

案例中输出的三个如下,可供参考理解

        1、新增一条数据:updateOne();【UpdateResult updateOne = collection.updateOne(eq, new Document("$set",new Document("age",20)));】

             输出结果:matchedCount=1, modifiedCount=1, upsertedId=null

        2、新增多条数据:uodateMany();【UpdateResult updateMany = collection.updateMany(eq, new Document("$set",new Document("age",20)));】

             输出结果:matchedCount=7, modifiedCount=1, upsertedId=null

        3、upsertedId:使upsertedId有值,当新增条件不成立的时候,设置这个值,就会新增一条新的数据。【UpdateResult updateMany1 = collection.updateMany(eq, new Document("$set",new Document("age",20)),new UpdateOptions().upsert(true));】

              输出结果:matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{value=631fe6fdcdfd423e2a54d588}

五、操作MongoDB数据库—— find数据

        语法: collection.find()//查找所有

                   collection.updateMany(eq, new Document("$set",new Document("age",20)));;//有条件查询

        具体实例如下

        //查询find
		FindIterable<Document> find = collection.find();
		System.out.println(find);
		
		//模糊查询 ^regex$
		Bson eq = Filters.regex("name", "张");
		FindIterable<Document> findmh = collection.find(eq);
		System.out.println(findmh);

六、全部代码展示

        项目结构【注意一部分一部分测试理解,导入参考驱动包,本项目lib下两个驱动包】

                

         实体类Student

package com.shang.Bean;

import java.util.Date;

public class Student {
	private Date birthday;
	private String  name;
	private String sex;
	private int age;
	
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date date) {
		this.birthday = date;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(Date birthday, String name, String sex, int age) {
		super();
		this.birthday = birthday;
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [birthday=" + birthday + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
	}

}

DaoUtil

package com.shang.Dao;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Set;

import org.bson.Document;

public class DocUtil {
	
	public static <T> Document ObjToDoc(T t){
		Document doc = new Document();
		Field[] fields = t.getClass().getDeclaredFields();
		if(fields != null) {
			for(int i = 0; i< fields.length;i++) {
				try {
					fields[i].setAccessible(true);
					String name = fields[i].getName();
					Object value = fields[i].get(t);
					doc.append(name, value);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
		}
		return doc;
	}
	
	public static <T> T DocToObj(Document doc,Class<T> t) {
		
		T obj = null;
		try {
			obj = t.newInstance();
			Set<String> keySet = doc.keySet();
			System.out.println(keySet);
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String next = iterator.next();
				String keyname = next.toLowerCase();
				if(!keyname.equals("_id")) {
					Field[] declaredFields = t.getDeclaredFields();
					Field declaredField = t.getDeclaredField(keyname);
					declaredField.setAccessible(true);
					declaredField.set(obj, doc.get(next));
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return obj;
	}
	

}

测试文件

package com.shang.test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.shang.Bean.Student;

public class test01 {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		//1.获取MongoDB的连接对象
		MongoClient mc = new MongoClient("localhost",27017);
		System.out.println(mc);
		//查看数据库中所有的库 数据库连接对象.listDatabaseNames();得到一个iterator,遍历
		MongoIterable<String> listDatabaseNames = mc.listDatabaseNames();
		MongoCursor<String> iterator = listDatabaseNames.iterator();
		while(iterator.hasNext()) {
			String next = iterator.next();
			System.out.println(next);
		}
		
		//2.获得库对象: 数据库连接对象.getDatabase("数据库名")
		MongoDatabase db = mc.getDatabase("myschool");
		System.out.println(db);
		
		
		//取到库中的集合 :库对象.listCollectionNames(); 遍历
		MongoIterable<String> listCollectionNames = db.listCollectionNames();
		for(String str:listCollectionNames) {
			System.out.println(str);
		}
		
		//3.获取对象
		MongoCollection<Document> collection = db.getCollection("student");
		System.out.println();

		//新增
		Document document = new Document();
		document.put("name", "张瑜");
		document.put("birthday", "2022-9-13");
		document.put("sex", "男");
		document.put("age", "18");
		//添加一条数据,没有返回值
		collection.insertOne(document);
		
		
		
		
		//一次性添加多条数据 insertMany();
		Document document1 = new Document();
		document1.put("name", "张瑜");
		document1.put("birthday", "2022-9-13");
		document1.put("sex", "男");
		document1.put("age", "18");
		Document document2 = new Document();
		document2.put("name", "婳樱");
		document2.put("birthday", "2022-9-13");
		document2.put("sex", "女");
		document2.put("age", "18");
		Document document3 = new Document();
		document3.put("name", "王黎");
		document3.put("birthday", "2022-9-13");
		document3.put("sex", "男");
		document3.put("age", "18");
		Document document4 = new Document();
		document4.put("name", "张瑜");
		document4.put("birthday", "2022-9-13");
		document4.put("sex", "男");
		document4.put("age", "18");
		Document document5 = new Document();
		document5.put("name", "张瑜");
		document5.put("birthday", "2022-9-13");
		document5.put("sex", "男");
		document5.put("age", "18");
		
		ArrayList<Document> list =new ArrayList<>();
		list.add(document1);
		list.add(document2);
		list.add(document3);
		list.add(document4);
		list.add(document5);
		collection.insertMany(list);
		
		//修改[学习过滤器Filters]
		Bson eq = Filters.eq("name","张瑜");
		UpdateResult updateOne = collection.updateOne(eq, new Document("$set",new Document("age",21)));
		System.out.println(updateOne);
		//输出结果matchedCount=1, modifiedCount=1, upsertedId=null
		
		UpdateResult updateMany = collection.updateMany(eq, new Document("$set",new Document("age",20)));
		System.out.println(updateMany);
		//输出结果:matchedCount=7, modifiedCount=1, upsertedId=null
		
		//使upsertid有值【matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{value=631fe6fdcdfd423e2a54d588}】
		UpdateResult updateMany1 = collection.updateMany(eq, new Document("$set",new Document("age",20)),new UpdateOptions().upsert(true));
		System.out.println(updateMany1);
		
		//Filters利用and/or方法将多个条件变成一个Bson格式作为条件,年龄大于20,小于等于30的学生性别改为保密
		Bson eq1 = Filters.gte("age",20);
		Bson lte = Filters.lte("age", 30);
		Bson and = Filters.and(eq1,lte);
		UpdateResult updateMany2 = collection.updateMany(and, new Document("$set",new Document("sex","保密")));
		System.out.println(updateMany2);
		
		//Inc给文件的字段加上100
		UpdateResult updateMany3 = collection.updateMany(and, new Document("$inc",new Document("age",100)));
		System.out.println(updateMany3);
		
		//删除
		Bson gt = Filters.gt("age", 100);
		Bson exists = Filters.exists("sex");
		Bson exists2 = Filters.exists("sex", false);
		DeleteResult deleteOne = collection.deleteOne(new Document("name","张瑜"));
		System.out.println(deleteOne);
		
		DeleteResult deleteOne2 = collection.deleteMany(gt);
		System.out.println(deleteOne2);
		
		DeleteResult deleteMany = collection.deleteMany(exists2);
		System.out.println(deleteMany);
		
		
		Student s=new Student();
		s.setAge(20);
		s.setBirthday(new Date());
		s.setSex("男");
		s.setName("十四");
		
		//JSON格式的转换
		Gson gson=new GsonBuilder().create();
		Document document1 = new Document();
		//将student对象转换为JSON格式
		String json=gson.toJson(s);
		//以JSON的格式将数据加入到MongoDB数据库中
		collection.insertOne(Document.parse(json));
		
		
		
		//查询find
		FindIterable<Document> find = collection.find();
		System.out.println(find);
		
		//模糊查询 ^regex$
		Bson eq = Filters.regex("name", "张");
		FindIterable<Document> findmh = collection.find(eq);
		System.out.println(findmh);
		
		//分页skip();
		Document document = new Document("birthday",-1);
		FindIterable<Document> find1= collection.find(eq).sort(document);
		for (Document doc :find1) {
			System.out.println(doc);
		}
		List<Student> slist=new ArrayList<>();
		MongoCursor<Document> iterator2 = find.iterator();
		Student s1=new Student();
		Document next = iterator2.next();
		s1.setSex("男");
		s1.setBirthday(new Date());
		s1.setAge(20);
		s.setName("花火");
		
		
		//参数一 JSON 字符串
		// 参数二 需要的对象的类型
		 json=next.toJson();
		System.out.println(json);
		gson.fromJson(json, Student.class);
		slist.add(s1);
		for(Student ss:slist) {
			System.out.println(ss);
		}
		
		
		mc.close();
	

}
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐