Record the use process of MongoDB, from the introduction of database to the application of actual code
reference material:
https://www.runoob.com/mongodb/mongodb-connections.html
1 overview of mongodb
1. Introduction to mongodb
MongoDB is an open source database system based on distributed file storage written in C + + language. It is mainly to provide scalable high-performance data storage solutions for WEB applications.
MongoDB stores data as a document, and the data structure consists of key value (key = > value) pairs. A MongoDB document is similar to a JSON object. Field values can contain other documents, arrays, and document arrays.
2 MongoDB system
Compare the structure of MongoDB with that of relational database MySQL:
MySQL | MongoDB |
---|---|
Database database | Database database |
table | Collection collection |
Row table row | Document document |
column row | field a property of the document |
Index index | Index index |
Table connection | Cross collection queries are not supported |
Primary key primary key | primary key |
3MongoDB data type
The small storage unit of MongoDB is the document object. Data is stored on disk in the format of bson (binary JSON) document in MongoDB
data type | explain |
---|---|
String | character string |
Integer | Integer value |
Boolean | Boolean value |
Double | Double precision floating point value |
Min/Max keys | Compares a value to the lowest and highest values of the BSON element |
Array | Used to store an array or list or multiple values as a key |
Timestamp | time stamp |
Object | For embedded documents |
Null | Used to create null values |
Symbol | Symbol |
Date | Date time |
Object ID | Object ID |
Binary Data | binary data |
Code | Code type |
Regular expression | Regular expression type |
2. Configuration description of mongodb
1 Windows installation steps
As mongodb-win32-x86_64-2008plus-ssl-4.0.12.zip as an example
1. Download MongoDB software
Download from the official website:
https://www.mongodb.com/try/download/community
2 unzip the package
Unzip mongodb-win32-x86_64-2008plus-ssl-4.0.12.zip to get mongodb-win32-x86_64-2008plus-ssl-4.0.12 file directory
3 create files to store logs and configuration files
Create the log directory and config directory. Create the configuration file mongod.conf in the config directory. The contents are as follows:
systemLog: destination: file # The following addresses cannot use \ backslashes, but slashes/ # Change to log directory address path: "D:/mongodb-win32-x86_64-2008plus-ssl-4.0.12/log/mongod.log" logAppend: true net: port: 27017 bindIp: "127.0.0.1" storage: # Modify the db address of your own database dbPath: "D:/mongodb-win32-x86_64-2008plus-ssl-4.0.12/data/db" journal: enabled: true
4 start service
Server start
Enter the bin directory of the file, use the cmd command in the address bar, enter the black window, and enter the command: mongod --config... / config/mongod.conf
Client startup
Enter the file bin directory, use the cmd command in the address bar, enter the black window, and enter the command: mongo --host=127.0.0.1 --port=27017
2 MongoDB connection
Standard URI syntax for connecting MongoDB service in Code:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
- mongodb: / / fixed format
- username:password @ optional. If set, the driver will try to log in to the database after connecting to the database server
- host1 must specify at least one host. host1 is the only one to fill in this URI. It specifies the address of the server to connect to. If you want to connect a replica set, specify multiple host addresses
- portX optional specified port. If it is not filled in, the default value is 27017
- Database if username:password @ is specified, connect and verify login to the specified database. If not specified, the test database is opened by default
- ? Options connection options. If / database is not used, it needs to be preceded by /. All connection options are key value pairs name=value, and key value pairs are connected through & or; (semicolon) separated
option | describe |
---|---|
replicaSet=name | Verify the name of the replica set. Impliesconnect=replicaSet. |
slaveOk=true|false | true: in connect=direct mode, the driver will connect to the first machine, even if the server is not the master. In the connect=replicaSet mode, the driver will send all write requests to the master and distribute the read operations to other slave servers. false: in connect=direct mode, the driver will automatically find the primary server. In connect=replicaSet mode, the driver only connects to the primary server, and all read-write commands are connected to the primary server. |
safe=true|false | true: after performing the update operation, the driver will send the getLastError command to ensure that the update is successful. (also refer to wtimeoutMS) false: after each update, the driver will not send getLastError to ensure that the update is successful |
w=n | Add {W: n} driver to getLastError command. Apply to safe=true |
wtimeoutMS=ms | Add {wtimeout: Ms} to the getlasterror command. Apply to safe=true |
fsync=true|false | True: add {fsync: true} to the getlasterror command. Apply to safe=true false: the driver will not be added to the getLastError command. |
journal=true|false | If set to true, synchronize to the journal (write to the entity before submitting to the database). Apply to safe=true |
connectTimeoutMS=ms | Time the connection can be opened |
socketTimeoutMS=ms | Time to send and receive sockets |
3 use of MongoDB in Java
Basic operations of Java and MongoDB
package com.demo.spring.mongoDB; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.bson.Document; import org.junit.After; import org.junit.Before; import org.junit.Test; import sun.net.www.content.audio.basic; /** * @Description: * @Author: cf * @Date: 2021/10/9 */ public class TestDemo { private MongoClientURI mongoClientURI; private MongoClient mongoClient; @Before public void init() { // No password mode // mongoClientURI = new MongoClientURI("mongodb://localhost:27017/mycol"); // Password mode mongoClientURI = new MongoClientURI("mongodb://cf:123456@localhost:27017/mycol"); mongoClient = new MongoClient(mongoClientURI); System.out.println("mongoClient Object generation"); // //Connect to mongodb service // mongoClient = new MongoClient("localhost", 27017); } @After public void drop() { mongoClient.close(); System.out.println("mongoClient Object destruction"); } // Regular query @Test public void getByPattern() { // Connect to mongodb service // MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); /** * Left matching: Pattern.compile("^ Wang. * $", pattern. Case_independent); * Right matching: Pattern.compile("^. * Wang $", pattern. Case_intrinsic); * Perfect match: Pattern.compile("^ Wang $", pattern. Case_intrinsic); * Fuzzy matching: Pattern.compile("^. * Wang. * $", pattern. Case_intrinsic); */ // Regular query: query all user names starting with Wang Pattern pattern = Pattern.compile("^king.*$", Pattern.CASE_INSENSITIVE); BasicDBObject searchCond = new BasicDBObject("description", new BasicDBObject("$regex", pattern)); MongoCursor<Document> cursor = users.find(searchCond).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Include query @Test public void getByInOrNin() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); // Include query: query the information with likes = 2, 3 and 10 List<Integer> searchList = new ArrayList<Integer>(); searchList.add(2); searchList.add(3); searchList.add(10); BasicDBObject searchCond = new BasicDBObject("likes", new BasicDBObject("$in", searchList)); MongoCursor<Document> cursor = users.find(searchCond).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Statistical query @Test public void getByCount() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); // Statistical query: check the total number of people with passwords like BasicDBObject filter = new BasicDBObject("likes", 2); long count = users.countDocuments(filter); System.out.println(count); } // Sort query @Test public void getByOrder() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); // Sorting Query: sorting rules: 1 (ascending), - 1 (descending) MongoCursor<Document> cursor = users.find().sort(new BasicDBObject("likes", 1)).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Projection query @Test public void getByProjection() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); // Projection query: display only_ The value of id and specified field information is meaningless MongoCursor<Document> cursor = users.find().projection(new BasicDBObject("likes", 1)) .iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Paging query @Test public void getByPage() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); // Paging query: skip the first one and query two pieces of data MongoCursor<Document> cursor = users.find().skip(1).limit(2).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Type query @Test public void getByType() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); // Type query: query all user information whose user name is string type BasicDBObject searchCond = new BasicDBObject(); // searchCond.append("likes", new BasicDBObject("$type", "string")); searchCond.append("likes", new BasicDBObject("$type", "int")); MongoCursor<Document> cursor = users.find(searchCond).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Join query: OR query @Test public void getByORCondition() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); BasicDBList condList = new BasicDBList(); condList.add(new BasicDBObject("likes", new BasicDBObject("$gt", 50))); condList.add(new BasicDBObject("likes", new BasicDBObject("$lt", 40))); // Condition query: user information with likes less than 200 and greater than 50 BasicDBObject searchCond = new BasicDBObject(); searchCond.put("$or", condList); MongoCursor<Document> cursor = users.find(searchCond).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Connection query: AND query @Test public void getByANDCondition() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase articledb = mongoClient.getDatabase("mycol"); MongoCollection<Document> users = articledb.getCollection("test"); BasicDBList condList = new BasicDBList(); condList.add(new BasicDBObject("likes", new BasicDBObject("$gt", 50))); condList.add(new BasicDBObject("likes", new BasicDBObject("$lt", 200))); // Condition query: user information with likes less than 200 and greater than 50 BasicDBObject searchCond = new BasicDBObject(); searchCond.put("$and", condList); MongoCursor<Document> cursor = users.find(searchCond).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Common operators for conditional query: equals, $ne, $gte, $lte, $gt, $lt // How is TODO equal to? Compare directly without adding operators (as follows) @Test public void getByCondition() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // If articledb exists, return articledb. If articledb does not exist, create articledb MongoDatabase articledb = mongoClient.getDatabase("mycol"); // If users exist, users will be returned. If not, users will be created MongoCollection<Document> users = articledb.getCollection("test"); // Condition query: query user information whose likes is not equal to 200 BasicDBObject searchCond = new BasicDBObject(); // Common operators: equals, $ne, $gte, $lte, $gt, $lt searchCond.append("likes", new BasicDBObject("$ne", 200)); // be equal to // searchCond.append("likes", 100); MongoCursor<Document> cursor = users.find(searchCond).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } // Delete the document, the first qualified / all qualified documents @Test public void deleteDocument() { try { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection<Document> collection = mongoDatabase.getCollection("test"); System.out.println("aggregate test Selection successful"); // deleteMany delete multiple // deleteOne delete a //Delete the first document that meets the criteria collection.deleteOne(Filters.eq("likes", 200)); //Delete all eligible documents collection.deleteMany(Filters.eq("likes", 200)); //Retrieve view results FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } // Update document @Test public void updateDocument() { try { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection<Document> collection = mongoDatabase.getCollection("test"); System.out.println("aggregate test Selection successful"); // If we only want to modify one field of the document, please use the $set operator to modify it, otherwise the other fields will disappear // updateMany modifies all qualified // updateOne modifies one that meets the conditions //Update the document and change the document with likes=100 in the document to likes=200 collection.updateMany( Filters.eq("likes", 100), new Document("$set", new Document("likes", 200))); //Retrieve view results FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } // consult your documentation @Test public void getDocument() { try { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection<Document> collection = mongoDatabase.getCollection("test"); System.out.println("aggregate test Selection successful"); //Retrieve all documents /** * 1. Get iterator finditeratable < document > * 2. Get cursor mongocursor < document > * 3. Traverse the retrieved document collection through the cursor * */ FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } // Insert document$ @Test public void insertDocument() { try { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection<Document> collection = mongoDatabase.getCollection("test"); System.out.println("aggregate test Selection successful"); //Insert document /** * 1. Create a document with the org.bson.Document parameter in the format of key value * 2. Create a document collection list < document > * 3. Insert the document collection into the database collection. Mongocollection. Insertmany (list < document >) can be used to insert a single document * */ Document document = new Document("title", "MongoDB"). append("description", "database"). append("likes", 100). append("by", "Fly"); List<Document> documents = new ArrayList<Document>(); documents.add(document); collection.insertMany(documents); System.out.println("Document inserted successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } // Get collection @Test public void getCollection() { try { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection<Document> collection = mongoDatabase.getCollection("test"); System.out.println("aggregate test Selection successful"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } // Create collection @Test public void createCollection() { try { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); mongoDatabase.createCollection("test"); System.out.println("Collection created successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } // Connection service 2 @Test public void test2() { try { //Connect to MongoDB service. If it is a remote connection, you can replace "localhost" with the IP address of the server //The two parameters of ServerAddress() are server address and port respectively ServerAddress serverAddress = new ServerAddress("localhost", 27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //The three parameters mongocredential. Createcramsha1credential() are user name, database name and password respectively MongoCredential credential = MongoCredential .createScramSha1Credential("username", "databaseName", "password".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //Obtain MongoDB connection through connection authentication MongoClient mongoClient = new MongoClient(addrs, credentials); //Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName"); System.out.println("Connect to database successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } // Connection service 1 @Test public void test1() { // Connect to mongodb service MongoClient mongoClient = new MongoClient("localhost", 27017); // Connect to database MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); } }