java connects mongoDB and adds deletes modifies and looks up the operation example in detail

  • 2021-07-13 05:12:11
  • OfStack

In this paper, an example is given to describe the connection between java and mongoDB, and the operation of adding, deleting, modifying and checking. Share it for your reference, as follows:

1. Install the MongoDB JDBC driver

Before using mongoDB in java, you first need to have a third-party driver package with java connected to mongoDB (jar package)

1) The maven project can be implemented by adding dependencies to pom. xml


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

2) Non-maven project jar package download address:

mongoDB jar package

2. Connect to the database

After adding the mongoDB JDBC driver to the project, you can operate on mongoDB.

1) Connect to the mongoDB service without authentication


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

Here, "localhost" indicates the server address connected, and 27017 is the port number. You can omit the port number and the system will default to 27017. Such as:


// Connect to  mongodb  Service, the default port number is 27017
MongoClient mongoClient = new MongoClient("localhost");

You can also omit both the server address and port number. The default server address is "localhost" and the port number is 27017. Such as:


// Connect to  mongodb  Service, which is connected to the localhost Server with port number 27017
MongoClient mongoClient = new MongoClient();

2) Connect to the mongoDB service through authentication


List<ServerAddress> adds = new ArrayList<>();
//ServerAddress() The two parameters are   Server address   And   Port 
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
adds.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<>();
//MongoCredential.createScramSha1Credential()3 Parameters are   User name   Database name   Password 
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
credentials.add(mongoCredential);
// Obtained through connection authentication MongoDB Connect 
MongoClient mongoClient = new MongoClient(adds, credentials);

ServerAddress() The two parameters "localhost" and 27017 are the server address and port, respectively.

MongoCredential.createScramSha1Credential() The three parameters "username", "databaseName" and "password". toCharArray () are the user name database name password respectively.

3) Connect to the database


// Connect to a database 
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");

Here, "test" indicates the database name. If the specified database does not exist, mongoDB will create the database when you insert the document for the first time.

4) Packaging into a tool class

Since all database connection operations require these two steps, we can encapsulate these two steps into a tool class.


import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
//mongodb  Connection database tool class 
public class MongoDBUtil {
  // Getting Connection Database Objects Without Authentication 
  public static MongoDatabase getConnect(){
    // Connect to  mongodb  Services 
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    // Connect to a database 
    MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
    // Returns the Connection Database Object 
    return mongoDatabase;
  }
  // Require password authentication to connect 
  public static MongoDatabase getConnect2(){
    List<ServerAddress> adds = new ArrayList<>();
    //ServerAddress() The two parameters are   Server address   And   Port 
    ServerAddress serverAddress = new ServerAddress("localhost", 27017);
    adds.add(serverAddress);
    List<MongoCredential> credentials = new ArrayList<>();
    //MongoCredential.createScramSha1Credential()3 Parameters are   User name   Database name   Password 
    MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
    credentials.add(mongoCredential);
    // Obtained through connection authentication MongoDB Connect 
    MongoClient mongoClient = new MongoClient(adds, credentials);
    // Connect to a database 
    MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
    // Returns the Connection Database Object 
    return mongoDatabase;
  }
}

3. Carry out CRUD on the database

The data in mongoDB is saved in a document (corresponding to 1 row in a relational database table), which in turn is saved in a collection (corresponding to a relational database table).

1) Get the collection

To perform CRUD operations on data, you must first obtain the collection of operations.


// Get the collection 
MongoCollection<Document> collection = MongoDBUtil.getConnect().getCollection("user");

Here, "user" indicates the name of the collection. If the specified collection does not exist, mongoDB will create the collection when you insert the document for the first time.

2) Create a document

To insert a document, you first need to create a document object


// Create a document 
Document document = new Document("name"," Zhang 3")
.append("sex", " Male ")
.append("age", 18);

3) Insert a document

Insert a document using the MongoCollection object's insertOne() Method, which receives 1 Document object as the data to be inserted


// Insert 1 Documents 
@Test
public void insertOneTest(){
  // Get the database connection object 
  MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
  // Get the collection 
  MongoCollection<Document> collection = mongoDatabase.getCollection("user");
  // Data to insert 
  Document document = new Document("name"," Zhang 3")
              .append("sex", " Male ")
              .append("age", 18);
  // Insert 1 Documents 
  collection.insertOne(document);
}

Insert multiple documents, using the MongoCollection object's insertMany() Method, which receives an List object of data type Document as the data to be inserted


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

0

4) Delete the document

Delete a single document that matches the filter, using the MongoCollection object's deleteOne() Method, which receives an object of data type Bson as a filter to filter out documents to be deleted. Then delete the first one. To facilitate the creation of filter objects, the JDBC driver provides the Filters class.


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

1

Delete all documents that match the filter, using the MongoCollection object's deleteMany() Method, which receives an object of data type Bson as a filter to filter out documents to be deleted. Then delete all filtered documents.


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

2

5) Modify the document

Modify a single document using the MongoCollection object's updateOne() Method, which receives two parameters, the first of which is a filter of Bson to filter out the document to be modified, and the second of which is Bson to specify how to modify the filtered document. Then modify the first document filtered by the filter.


// Modify a single document 
@Test
public void updateOneTest(){
  // Get the database connection object 
  MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
  // Get the collection 
  MongoCollection<Document> collection = mongoDatabase.getCollection("user");
  // Modify filter 
  Bson filter = Filters.eq("name", " Zhang 3");
  // Specify the modified update document 
  Document document = new Document("$set", new Document("age", 100));
  // Modify a single document 
  collection.updateOne(filter, document);
}

Modify multiple documents, using the MongoCollection object's updateMany() Method, which receives two parameters, the first filter of data type Bson filters out the document to be modified, and the second parameter of data type Bson specifies how to modify the filtered document. Then modify all documents filtered out by the filter.


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

4

6) Query the document

Object using the MongoCollection object find() Method, which has multiple overloaded methods, and can use the find() Method to query all documents in the collection, or you can query qualified documents by passing a filter of type Bson. Each of these overloaded methods returns an object of type FindIterable, through which all the queried documents can be traversed.

Find all documents in the collection


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

5

Specify query filter query


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

6

Available through MongoCredential.createScramSha1Credential()0 Method to retrieve the first document from the query


// Connect to  mongodb  Services 
MongoClient mongoClient = new MongoClient("localhost", 27017);

7

4. Summary

At this point, the first basic operation of java to mongoDB is introduced. The steps to implement are: add driver = = > Connect to a service = = > Connect to database = = > Select Set = = > Performs an CRUD operation on the collection.

More readers interested in java can check the topics of this site: "Summary of Java Using JDBC to Operate Database", "Summary of Java+MySQL Database Programming", "Java Data Structure and Algorithm Tutorial", "Summary of Java File and Directory Operation Skills", "Summary of Java Operating DOM Node Operation Skills" and "Summary of Java Cache Operation Skills"

I hope this paper is helpful to everyone's java programming.


Related articles: