MongoDB runs from entry to database deletion---Mongo native java driver integration and simple CRUD

First, open the MongoDB connection on the cmd command line and use the test (replace your own library) library. View the data created in the previous article in the owner table. A json data structure of test data is posted here.

var owner1 = {
	name: "张三",
	age: 25,
	books: {
		name: "天涯明月刀",
		author: "古龙"
	},
	favorites: {
		movies: ["盗梦空间", "杀破狼", "羞羞的铁拳"],
		cites: ["北京", "上海", "深圳"]
	},
	salary: NumberDecimal("100.05")
};

 

--- The java program obtains the mongoDB database and collection connection

1. The program pom file introduces the mongoDB native java driver package. Update and clean the project.

<!-- mongoDB原生java驱动 -->
<!-- 3.5之后的版本,新增了对java的pojo的支持 -->
<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>3.5.0</version>
</dependency>

 2. Create a test service class. Declare 3 variables: MongoClient, MongoDatabase, MongoCollection, as shown in the figure:

import org.bson.Document;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;

/**
 * mongodb连接池
 */
private MongoClient client;

/**
 * mongoDB库
 */
private MongoDatabase db;

/**
 * mongoDB集合,泛型为mongoDB文档
 */
private MongoCollection<Document> mongoCollection;

first. The connection client provided by mongoClient for mongoDB provides a mongoDB connection pool internally, so there is no need to refer to third-party dependencies, and it is detailed in the official document: this client is thread-safe, so in most cases, it only needs to exist in the jvm A client instance.

The target library can be obtained from mongoClient and then connected to the target collection.

MongoCollection<Document>, the generic type is Document. In the mongoDB native driver, all data elements are documents--Document. The document does not limit the specific type, nor does it limit the number of attributes and attribute types in the document. Compare and understand with the java model reference.

3. Obtain the target mongo instance connection through mongoClient, and get the target library and collection connection.

    @Before // junit测试使用注解
	public void init() {
		// mongoDB实例ip, 端口(默认27017)
		client = new MongoClient("localhost", 27017);
		// 目标库
		db = client.getDatabase("las");
		// 目标集合
		mongoCollection = db.getCollection("users");
	}

After the mongoDB connection, the library and the collection are initialized, the simple CRUD implementation of the data in the java code starts.

 

--- Use native java driver to operate Document documents and implement simple CRUD

5. Added insert. For the data format, refer to the json data format at the beginning of this article.

    @Test
	public void insert() {
		Document doc = new Document();
		// -------- 基本属性 --------
		doc.append("name", "李六");
		doc.append("age", 17);
		doc.append("salary", new BigDecimal("5000.21"));

		// ------- 属性值为简单对象 -------
		Map<String, String> books = new HashMap<>();
		books.put("name", "北平往事");
		books.put("author", "不知道");
		doc.append("books", books);

		// ------------ 属性值为对象,内包含不同数据类型。数组集合等 ----------
		Map<String, Object> favorites = new HashMap<>();
		favorites.put("movies", Arrays.asList("三体", "人工智能", "终结者"));
		favorites.put("cites", Arrays.asList("河南", "湖南", "海南"));
		doc.append("favorites", favorites);

		// 使用init()方法内获取的目标集合连接实例,向该集合内插入一个文档
		mongoCollection.insertOne(doc);
	}

The junit test runs the insert method, queries db.owner.find() in cmd, and successfully adds a record.

6. Delete delete. Comments use relational sql language to explain the purpose, and post the code in mongoDB to achieve the same purpose.

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.model.Filters;    

    @Test
	public void delete() {
		// delete from owner where name = "张三"
        Bson f1 = Filters.eq("name", "张三");
        // 删除满足条件的所有文档
		DeleteResult result1 = mongoCollection
				.deleteMany(f1);
		LOG.info("删除了:: " + String.valueOf(result1));

		// delete from owner where age > 25 or age < 5
        Bson f2 = Filters.gt("age", 25)
        Bson f3 = Filters.lt("age", 5)
        Bson f4 = Filters.or(f2, f3)
        // 删除满足条件的所有文档
		DeleteResult result2 = mongoCollection.deleteMany(f4);
		LOG.info("第二次删除了 ::::  " + String.valueOf(result2));
	}

7. Update update.

import com.mongodb.client.result.UpdateResult;
import com.mongodb.client.model.Updates;

    @Test
	public void update() {
		// update owner set age = 4 where name = "王五"

        // 使用替换更新。注意此处与操作符更新区别。
        // Document doc = new Document("age", 4);
        // 使用操作符更新。注意此处与替换更新区别。
        Document doc = new Document("$set", new Document("age", 4));

        // 执行更新。
		UpdateResult result1 = mongoCollection.updateMany(
				Filters.eq("name", "王五"), doc);
        // 打印日志:匹配数量,更新数量。
		LOG.info(String.valueOf(result1.getMatchedCount()), "   ",
				String.valueOf(result1.getModifiedCount()));
        // -------------------------------------------------------------------------------

		// update owner set favorites.movies add "大片1" "大片2"  ---并非有效sql语句,仅为说明目的
		// where favorites.cites has "北京" or "纽约"
        // 使用Updates的addEachToSet方法,将传入的list内的每一个元素都add进目标属性的list最后
        Bson arrayToAdd = Updates.addEachToSet("favorites.movies",
						Arrays.asList("大片1", "大片2"));

        // 执行更新
		UpdateResult result2 = mongoCollection.updateMany(
				Filters.or(Filters.eq("favorites.cites", "北京"),
						Filters.eq("favorites.cites", "纽约")), arrayToAdd );
		LOG.info(String.valueOf(result2.getMatchedCount()), "   ",
				String.valueOf(result2.getModifiedCount()));
	}

Note: Replacing and updating new Document("age", 4) will update the document with name = "Wang Wu" to a document with only "age" attribute and a value of 4.

       The operator updates new Document("$set", new Document("age", 4)), and only the age attribute value in the document with name = "Wang Wu" will be modified to 4.

8. Query find. focus. All updates, deletes, require queries as conditions.

import com.mongodb.Block;
import com.mongodb.client.FindIterable;

    @Test
	public void find() {
        // 查询结果集合。必须使用final声明
		final List<Document> resultList = new ArrayList<>();
		// 查询结果块。Document类型
		Block<Document> block = new Block<Document>() {
			// 调用,将每一个Document传入此中
			@Override
			public void apply(Document t) {
				LOG.info(t.toJson());
				resultList.add(t);
			}
		};

		// select * from owner where favorites.cites has "上海" "华盛顿"
		FindIterable<Document> result1 = mongoCollection.find(
				Filters.all("favorites.cites", Arrays.asList("深圳", "北京")));

        // find()方法查到返回的结果为游标,需要将此遍历并使用Block接受转换为Document
		result1.forEach(block);
		LOG.info("查询1---------------------");
		LOG.info(String.valueOf(resultList.size()));

		// 清空查询结果集合
		resultList.clear();

		// select * from owner
		// where name like '%李%'
		// and (favorites.cites has '印度' or favorites.cites has 纽约)
		String regex = ".*李.*"; // mongoDB内的like模糊查询。使用正则表达式完成
		Bson f1 = Filters.regex("name", regex);

		Bson f2 = Filters.or(Filters.eq("favorites.cites", "印度"),
				Filters.eq("favorites.cites", "纽约"));

		FindIterable<Document> result2 = mongoCollection
				.find(Filters.and(f1, f2));
		result2.forEach(block);

		LOG.info("查询2---------------------");
		LOG.info(String.valueOf(resultList.size()));
	}

9. In the above methods, the Filters, Updates, etc. used include some that will be used later. The data manipulation classes provided by mongoDB are also marked in the class description: it is recommended to import all methods statically and provide them in the class. You can omit the class name when using a static method.

Note: Use delete and replace updates carefully to prevent data loss! ! ! If you accidentally slip, please refer to the title of this article to solve it~~.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325309847&siteId=291194637