MongoDB Running from Initial to Delete Library--mongo Native java Driver Integration and Simple CRUD

Keywords: MongoDB Java Attribute JSON

First, the cmd command line opens the MongoDB connection, and use the test (self-changing libraries) library. View the data created in the previous article in the owner table. Here is a json data structure for test data.

var owner1 = {
	name: "Zhang San",
	age: 25,
	books: {
		name: "Tianya Mingyue Knife",
		author: "Gulong"
	},
	favorites: {
		movies: ["Inception", "SPL", "A shy iron fist"],
		cites: ["Beijing", "Shanghai", "Shenzhen"]
	},
	salary: NumberDecimal("100.05")
};

 

- java program to acquire mongoDB database and set connection

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

<! - MongoDB native java driver
 <! - Version after 3.5 adds support for pojo in java - >.
<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>3.5.0</version>
</dependency>

2. Establish the test service class. Declare three variables: MongoClient, MongoDatabase, and 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 Connection pool
 */
private MongoClient client;

/**
 * mongoDB library
 */
private MongoDatabase db;

/**
 * mongoDB Collection, generic as mongoDB document
 */
private MongoCollection<Document> mongoCollection;

First. The connection client provided by mongoClient for mongoDB provides a mongoDB connection pool internally, which does not need to refer to third-party dependencies. It is detailed in the official document that this client is thread-safe, so in most cases, only one client instance is needed in jvm.

Target libraries can be obtained from mongoClient, and then target collections can be connected.

MongoCollection < Document >, generic type is Document. Within the mongoDB native driver, all data elements are documents -- Documents. Documents do not limit specific types, nor do they limit the number and types of attributes in documents. Compare with java model.

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

    @Before // Annotations for junit test usage
	public void init() {
		// mongoDB instance ip, port (default 27017)
		client = new MongoClient("localhost", 27017);
		// Target library
		db = client.getDatabase("las");
		// Target set
		mongoCollection = db.getCollection("users");
	}

After the mongoDB connection and the initialization of libraries and collections are completed, a simple CRUD implementation of data in java code is started.

 

Using native java driver to manipulate Document documents and realize simple CRUD

5. Add insert. The data format refers to the json data format at the beginning of this article.

    @Test
	public void insert() {
		Document doc = new Document();
		// ----------- Basic Attribute----------------------------------------------------------------------------------------------------
		doc.append("name", "Li Liu");
		doc.append("age", 17);
		doc.append("salary", new BigDecimal("5000.21"));

		// The attribute value is a simple object.
		Map<String, String> books = new HashMap<>();
		books.put("name", "Past events in Peking");
		books.put("author", "Hear nothing of");
		doc.append("books", books);

		// The attribute value is an object, which contains different data types. Array sets, etc. ------------------------------------------------------------------------------------------------------------
		Map<String, Object> favorites = new HashMap<>();
		favorites.put("movies", Arrays.asList("Trisomy", "Artificial intelligence", "Terminator"));
		favorites.put("cites", Arrays.asList("Henan", "Hunan", "Hainan"));
		doc.append("favorites", favorites);

		// Insert a document into the collection by connecting instances of the target collection obtained in the init() method
		mongoCollection.insertOne(doc);
	}

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

6. Delete delete. Annotation uses relational sql language to explain the purpose, and pastes out the same purpose code in mongoDB.

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

    @Test
	public void delete() {
		// delete from owner where name = Zhang San
        Bson f1 = Filters.eq("name", "Zhang San");
        // Delete all documents that meet the criteria
		DeleteResult result1 = mongoCollection
				.deleteMany(f1);
		LOG.info("Deleted:: " + 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)
        // Delete all documents that meet the criteria
		DeleteResult result2 = mongoCollection.deleteMany(f4);
		LOG.info("The second deletion ::::  " + 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 = Wang Wu

        // Use replacement updates. Note the difference between this and operator updates.
        // Document doc = new Document("age", 4);
        // Update with an operator. Note the difference between this and replacement updates.
        Document doc = new Document("$set", new Document("age", 4));

        // Perform updates.
		UpdateResult result1 = mongoCollection.updateMany(
				Filters.eq("name", "Wang Wu"), doc);
        // Print logs: match number, update number.
		LOG.info(String.valueOf(result1.getMatchedCount()), "   ",
				String.valueOf(result1.getModifiedCount()));
        // -------------------------------------------------------------------------------

		// update owner set favorites.movies add "Block 1" and "Block 2" - - not valid sql statements, just for illustrative purposes
		// where favorites.cites has "Beijing" or "New York"
        // Using the addEachToSet method of Updates, each element in the incoming list is added to the end of the list of the target attribute.
        Bson arrayToAdd = Updates.addEachToSet("favorites.movies",
						Arrays.asList("Blockbuster 1", "Blockbuster 2"));

        // Execution update
		UpdateResult result2 = mongoCollection.updateMany(
				Filters.or(Filters.eq("favorites.cites", "Beijing"),
						Filters.eq("favorites.cites", "New York")), arrayToAdd );
		LOG.info(String.valueOf(result2.getMatchedCount()), "   ",
				String.valueOf(result2.getModifiedCount()));
	}

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

The operator updates the new Document("$set", new Document("age", 4)) to modify only the age attribute value of the document name d = Wang Wu to 4.

8. Query find. A key. All updates, deletions and queries are required as conditions.

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

    @Test
	public void find() {
        // Query result set. The final declaration must be used
		final List<Document> resultList = new ArrayList<>();
		// Query result block. Document type
		Block<Document> block = new Block<Document>() {
			// Call each Document into this
			@Override
			public void apply(Document t) {
				LOG.info(t.toJson());
				resultList.add(t);
			}
		};

		// select * from owner where favorites.cites has "Shanghai" and "Washington"
		FindIterable<Document> result1 = mongoCollection.find(
				Filters.all("favorites.cites", Arrays.asList("Shenzhen", "Beijing")));

        // The find() method finds that the returned result is a cursor, which needs to be traversed and converted to Document using Block acceptance
		result1.forEach(block);
		LOG.info("Query 1---------------------");
		LOG.info(String.valueOf(resultList.size()));

		// Empty the query result set
		resultList.clear();

		// select * from owner
		// where name like'% Li%'
		// and (favorites.cites has'India'or favorites.cites has New York)
		String regex = ".*plum.*"; // like fuzzy queries in mongoDB. Complete with regular expressions
		Bson f1 = Filters.regex("name", regex);

		Bson f2 = Filters.or(Filters.eq("favorites.cites", "India"),
				Filters.eq("favorites.cites", "New York"));

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

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

9. Among the methods mentioned above, Filters, Updates and so on include some that will be used later. The data operation classes provided by mongoDB also indicate in the class description that it is recommended to import all methods statically and omit the class name when using the static methods provided in the class.

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

Posted by mark103 on Thu, 16 May 2019 00:42:55 -0700