当前位置: 首页 > article >正文

MongoDB (一) Java使用MongoDB[CURD]

0.引入jar包获取

<dependencies>
	<dependency>
		<groupId>org.mongodb</groupId> 
		<artifactId>mongo-java-driver</artifactId>
		<version>3.12.13</version>
	</dependency>
</dependencies>

1.创建连接

1.1.无密码连接

1.1.1.使用com.mongodb.MongoClient

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.MongoClient;

public class MongoDBTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	
	public static void main(String[] args) {
		try {
			MongoClient mongoClient = new MongoClient();
			// 或者
			MongoClient mongoClient = new MongoClient(IP, PORT);
		}
	}
}

1.1.2.使用com.mongodb.MongoClient

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

public class MongoDBClientTest {
	public static void main(String[] args) {
		try {
			//本地
			MongoClient mongoClient = MongoClients.create();
			// 或者
			MongoClient mongoClient = MongoClients.create("mongodb://localhost");
			// 或者
			MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
			// 或者
			MongoClient mongoClient = MongoClients.create(new ConnectionString("mongodb://localhost"));
			// 或者
			MongoClient mongoClient = MongoClients.create(new ConnectionString("mongodb://localhost:27017"));
		}
	}
}

1.2.有密码连接

后续更新

2.创建DB

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

public class MongoDBTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			MongoDatabase db = mongoClient.getDatabase(DATABASE);
		}
	}
}

说明: mongodb没有创建数据库的方法, 可以通过getDatabase方法来实现, 如果该数据库存在,则不会创建新的数据库, 如果不存在, 则会自动创建.

2.集合

2.1.创建集合

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			MongoDatabase db = mongoClient.getDatabase(DATABASE);
			db.createCollection(COLLECTION);
		}
	}
}

2.2.获取集合

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			MongoDatabase db = mongoClient.getDatabase(DATABASE);
			MongoCollection<Document> collection = db.getCollection(COLLECTION);
			// 获取集合列表
			MongoIterable<String> listCollectionNames = db.listCollectionNames();
		}
	}
}

2.3.删除集合

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			MongoDatabase db = mongoClient.getDatabase(DATABASE);
			MongoCollection<Document> collection = db.getCollection(COLLECTION);
			collection.drop();
		}
	}
}

3.新增

3.1.单个新增

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBInsertTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			insertOneData(mongoClient);
		}
	}
	
	public static void insertOneData(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		Document document = new Document().append("reel_id", "X0003").append("name", "B_3").append("qty", 120);
		//Document document = new Document().append("_id", 1).append("reel_id", "X0003").append("name", "B_3").append("QTY", 120);
		collection.insertOne(document);
		
	}
	
	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

说明:
没有设置ID, 则数据库会自动生成一个唯一ID;
设置了ID, 如果数据库没有该ID, 则为新增操作, 如果有该ID, 则抛出异常

3.2.多个新增

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

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBInsertTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			insertManyData(mongoClient);
		}
	}
	
	public static void insertManyData(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		List<Document> documents = new ArrayList<Document>();
		int begin = 4;
		for (int i = begin; i < begin + 3; i++) {
			Document document = new Document().append("reel_id", "X000" + i).append("name", "B_" + i).append("QTY", 120 + i * 10);
			documents.add(document);
		}
		collection.insertMany(documents);
	}
	
	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

4.查询

4.1.基本查询

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBQueryTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";

	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			basicQuery(mongoClient);
		}
	}
	
	public static void basicQuery(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		FindIterable<Document> findIterable = collection.find();
		findIterable.forEach(new Consumer<Document>() {
			@Override
			public void accept(Document document) {
				String name = document.getString("name");
				System.out.println(name);
			}
		});
	}
	
	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

4.2.表达式查询

4.2.1.使用Bson设置查询条件

可以使用com.mongodb.BasicDBObject类, 或者org.bson.Document类, 因为他们都实现 org.bson.conversions.Bson

import java.util.function.Consumer;
import java.util.regex.Pattern;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBQueryTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			regexQuery(mongoClient);
		}
	}
	
	public static void regexQuery(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
			
		BasicDBObject regexQuery = new BasicDBObject();
		// $regex类似于like查询
		regexQuery.put("name", new BasicDBObject("$regex", "R.*"));
		// 其中的R.*也可以使用java.util.regex.Pattern替换, 如下:
		// Pattern compile = Pattern.compile("^R");
		// regexQuery.put("name", new BasicDBObject("$regex", compile));
		
		// $lte  $lt $qt $qte等比较运算符
		regexQuery.put("qty", new BasicDBObject("$lte", 100));
	
		// 也可以使用Document替换BasicDBObject
		/**
		Document regexQuery = new Document();
		regexQuery.put("name", new Document("$regex", "R.*"));
		*/
		
		FindIterable<Document> findIterable = collection.find(regexQuery);
		findIterable.forEach(new Consumer<Document>() {
			@Override
			public void accept(Document document) {
				String name = document.getString("name");
				System.out.println(name);
			}
		});
	}

	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

4.2.2.使用Filter设置查询条件

import java.util.function.Consumer;

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

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MongoDBQueryTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			filterQuery(mongoClient);
		}
	}
	
	public static void filterQuery(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		Bson lt = Filters.lte("qty", 100);
		FindIterable<Document> findIterable = collection.find(lt);
		findIterable.forEach(new Consumer<Document>() {
			@Override
			public void accept(Document document) {
				String name = document.getString("name");
				Integer qty = document.getInteger("qty");
				System.out.println(name + "->" + qty);
			}
		});
	}
	
	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

结果:

R_1->100
A_2->50

4.3.排序查询

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBQueryTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			sortQuery(mongoClient);
		}
	}
	
	public static void sortQuery(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		FindIterable<Document> findIterable = collection.find().sort(new BasicDBObject().append("qty", 1).append("name", -1));
		findIterable.forEach(new Consumer<Document>() {
			@Override
			public void accept(Document document) {
				String name = document.getString("name");
				System.out.println(name);
			}
		});
	}
	
	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

说明: sort方法第一个参数为字段名, 第二个参数 -1是倒序查询, 1是顺序查询

4.4.分页查询

import java.util.function.Consumer;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBQueryTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			pagingQuery(mongoClient);
		}
	}
	
	public static void pagingQuery(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		FindIterable<Document> findIterable = collection.find().limit(10).skip(0);
		findIterable.forEach(new Consumer<Document>() {
			@Override
			public void accept(Document document) {
				String name = document.getString("name");
				System.out.println(name);
			}
		});
	}
	
	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

说明: limit为查询的数量, skip为跳过的数量, 如果是0, 则查询的时候是从第1个数开始.

4.5.设置查询返回字段

import java.util.function.Consumer;

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

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;

public class MongoDBQueryTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			setReturnFiledQuery(mongoClient);
		}
	}
	
	public static void setReturnFiledQuery(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		// 设置包含字段返回
		Bson include = Projections.include("name", "qty");
		// 去除部分字段返回
		Bson exclude = Projections.exclude("_id");
		// 也可以使用excludeId方法代替exclude("_id")
		//Bson excludeId = Projections.excludeId();

		//include 和 exclude可以只设置一种
		Bson projection = Projections.fields(include, exclude);
		
		FindIterable<Document> findIterable = collection.find().projection(projection);
		findIterable.forEach(new Consumer<Document>() {
			@Override
			public void accept(Document document) {
				System.out.println(document);
			}
		});
	}
	
	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

结果如下:

Document{{name=R_1, qty=100}}
Document{{name=A_2, qty=50}}

5.修改

5.1.单个修改

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

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;

public class MongoDBUpdateTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			updateOne(mongoClient);
		}
	}
	
	public static void updateOne(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		// 1.filter部分
		Bson filters = Filters.lt("qty", 100);
		// 或者使用BasicDBObject
		//BasicDBObject filters = new BasicDBObject().append("qty", new BasicDBObject("$lt", 100));
		
		// 2.update部分
		Document document = new Document().append("$set", new Document().append("qty", 30));
		// 或者使用BasicDBObject也可以
		//BasicDBObject document = new BasicDBObject().append("$set", new Document().append("qty", 40));
		// 或者使用Updates.combine方法也可以
		// Bson updateDoc = Updates.combine(Updates.set("qty", 60));

		// 3.update db
		UpdateResult updateResult = collection.updateOne(filters, document);
		// 还可以配置: 如果不存在该数据, 则新增一条数据
		//UpdateOptions options = new UpdateOptions().upsert(true);
		//UpdateResult updateResult = collection.updateMany(filter, updateDoc, options);
		
		System.out.println(updateResult);
	}

	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

5.2.多个修改

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

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;

public class MongoDBUpdateTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			updateMany(mongoClient);
		}
	}
	
	public static void updateMany(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		Bson filter = Filters.lt("qty", 100);
		Bson updateDoc = Updates.combine(Updates.set("qty", 60));
		UpdateResult updateResult = collection.updateMany(filter, updateDoc);
		System.out.println(updateResult);
	}

	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

5.3.替换(慎用)

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

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;

public class MongoDBUpdateTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			replaceOne(mongoClient);
		}
	}
	
	public static void replaceOne(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		Bson filter = Filters.lt("qty", 100);
		Document updateDoc = new Document()
				.append("qty", 20);
		UpdateResult updateResult = collection.replaceOne(filter, updateDoc);
		System.out.println(updateResult);
	}

	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

说明: 该方法慎用, 使用该方法替换之后, 只有设置的字段会被修改替换, 其他的字段等同于被删除, 仅剩下_id和设置的字段.

6.删除

6.1.删除单个

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

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;

public class MongoDBDeleteTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			deleteOne(mongoClient);
		}
	}
	
	public static void deleteOne(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		Bson filter = Filters.lte("qty", 20);
		DeleteResult deleteResult = collection.deleteOne(filter);
		System.out.println(deleteResult);
	}

	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

结果

AcknowledgedDeleteResult{deletedCount=1}

6.2.删除多个

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

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;

public class MongoDBDeleteTest {
	private final static String IP = "localhost";
	private final static int PORT = 27017;
	private final static String DATABASE = "database";
	private final static String COLLECTION = "reel";
	
	public static void main(String[] args) {
		try (MongoClient mongoClient = new MongoClient(IP, PORT)) {
			deleteMany(mongoClient);
		}
	}
	
	public static void deleteMany(MongoClient mongoClient) {
		MongoCollection<Document> collection = getCollection(mongoClient);
		Bson filter = Filters.lt("qty", 100);
		DeleteResult deleteResult = collection.deleteMany(filter);
		System.out.println(deleteResult);
	}

	private static MongoCollection<Document> getCollection(MongoClient mongoClient) {
		MongoDatabase db = mongoClient.getDatabase(DATABASE);
		MongoCollection<Document> collection = db.getCollection(COLLECTION);
		return collection;
	}
}

结果

AcknowledgedDeleteResult{deletedCount=2}

http://www.kler.cn/a/15519.html

相关文章:

  • Java爬虫(Jsoup)详解
  • 基于Java和Vue实现的上门做饭系统上门做饭软件厨师上门app
  • Python 正则表达式使用指南
  • 探索Python网络请求新纪元:httpx库的崛起
  • 基于 CentOS7.6 的 Docker 下载常用的容器(MySQLRedisMongoDB),解决拉取容器镜像失败问题
  • Oracle 19c PDB克隆后出现Warning: PDB altered with errors受限模式处理
  • python@可变对象和不可变对象@按值传递和引用传递@python运行可视化工具
  • Leetcode力扣秋招刷题路-0852
  • 优思学院|精益生产为企业带来革命性转变的效益
  • Linux centos重装yum
  • GCM与CCM的的规格和加解密过程
  • 网页爬虫之WebPack模块化解密(JS逆向)
  • 学习笔记-主成分分析法
  • SpringBoot+Vue3实现登录验证码功能
  • CentOS计划任务的用法
  • 学系统集成项目管理工程师(中项)系列13a_人力资源管理(上)
  • Whistle安装与使用
  • javaEE+mysql学生竞赛管理系统
  • 亚马逊广告怎么做?广告效果如何提升?
  • 六级英语历年真题单词--按年份分类--持续更新中...
  • 【Java笔试强训 8】
  • 文件 IO 操作
  • jQuery知识点三
  • Linux命令集(Linux常用命令--cat指令篇)
  • 中级软件设计师备考---信息系统安全
  • 最新国内免费chatgpt 的试用方法