This article introduces how to complete MongoDB data operations on the MongoDB console. We have a comprehensive understanding and understanding of MongoDB through the previous article. Now we use Java to operate M.
This article introduces how to complete MongoDB data operations on the MongoDB console. We have a comprehensive understanding and understanding of MongoDB through the previous article. Now we use Java to operate M.
Previous Article: describes how to complete MongoDB data operations on the MongoDB console. Through the previous article, we have a comprehensive understanding and understanding of MongoDB. Now we use Java to operate MongoDB data.
Development Environment:
System: Windows
IDE: eclipse and MyEclipse 8
Database: mongoDB
Development dependency Library:
JavaEE5, mongo-2.5.3.jar, junit-4.8.2.jar
I. Preparations
1. First, download the driver packages supported by mongoDB for Java.
Driver Pack: https://github.com/mongodb/mongo-java-driver/downloads
MongoDB's Java-related support and technology: + Language + Center
Driver source code download: https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip
Source code: https://github.com/mongodb/mongo-java-driver
2. Create a JavaProject project to import the downloaded driver package. You can use mongoDB in Java. The directory is as follows:
Ii. Java MongoDB operation example
Before this example, you can start the mongod.exe service. After the service is started, the following program can be successfully executed;
1. Create SimpleTest. java to complete simple mongoDB database operations
In this way, a MongoDB database connection object is created, which is connected to the localhost address of the current machine by default, and the port is 27017.
DB db = mongo. getDB ("test ");
In this way, a database named test is obtained. If this database is not created in mongoDB, it can run normally. If you have read the previous article, you will know that mongoDB can add data without creating this database. When this database is not added, mongoDB automatically creates the current database.
After obtaining the db, we will get a "clustered collection DBCollection" and use the getCollection method of the db object.
In this way, a DBCollection is obtained, which is equivalent to the "table" of our database ".
Query all data
Complete source code
2. To complete the CRUD operation, first create MongoDB4CRUDTest. java. The basic test code is as follows:
3. Add operation
Before adding an operation, we need to write a query method to query all the data. The Code is as follows:
4. delete data
5. modify data
6. query data
MongoDB does not support joint queries and subqueries, which must be completed in the program. Filter the query result set in the Java query.
7. Other operations
Now, we will introduce so many Java operations on MongoDB. You need to study other things on your own. The above operations on MongoDB are common and relatively simple.