Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Record the process of using MongoDB, from database introduction to actual code application.

References:

www.runoob.com/mongodb/mon…

1 Overview of MongoDB

1 introduction of directing

MongoDB is an open source database system based on distributed file storage written in C++ language, mainly to provide scalable high-performance data storage solutions for WEB applications.

MongoDB stores data as a document. The data structure consists of key=>value pairs. MongoDB documents are similar to JSON objects. Field values can contain other documents, arrays, and document arrays.

2 directing system

Compare the structure of MongoDB with that of relational database MySQL:

MySQL MongoDB
Database database Database database
Table table The collection collection
Row Indicates the row of the table The document document
Column A column in the row Field document property
The index index The index index
Table joins Cross-collection queries are not supported
Primary key primary key primary key

3MongoDB Data type

The small storage unit of MongoDB is document object. Data is stored on disk in the format of BSON(binary-JSON) document in MongoDB.

The data type instructions
String string
Integer integer
Boolean Boolean value
Double A double precision floating point value
Min/Max keys Compare a value to the lowest and highest values of a BSON element
Array Use to store an array or list or multiple values as a key
Timestamp The time stamp
Object For inline documents
Null Used to create null values
Symbol symbol
Date Date/time
Object ID The object ID
Binary Data Binary data
Code Code type
Regular expression Regular expression type

2 MongoDB configuration Description

1 Windows Installation Procedure

By directing a win32 – x86_64-2008 plus – SSL – 4.0.12. Zip, for example

1 Download the MongoDB software

Official website download:

www.mongodb.com/try/downloa…

2 Decompress the package

Mongodb-win32-x86_64-2008plus-ssl-4.0.12. zip = mongodb-win32-x86_64-2008plus-ssl-4.0.12

3 Create a file to store logs and configuration files

Create the log directory and config directory. Create the configuration file mongod. Conf. in the config directory as follows:

SystemLog: destination: file # do not use \ backslash / # to change the path of the log directory: "D:/mongodb-win32-x86_64-2008plus-ssl-4.0.12/log/mongod.log" logAppend: true net: port: 27017 bindIp: DbPath: "D:/mongodb-win32-x86_64-2008plus-ssl-4.0.12/data/db" journal: enabled: trueCopy the code

4 Starting services

Server startup

Go to the bin directory and run the CMD command in the address bar to go to the black window and enter the command: mongod –config… /config/mongod.conf

Client startup

Go to the bin directory, run CMD in the address bar, and enter mongo –host=127.0.0.1 –port=27017 in the black window

2 mongo connection

Standard URI syntax for connecting to MongoDB services in code:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

  • Mongodb :// fixed format
  • Username :password@ Optional. If this parameter is 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 be entered in this URI. It specifies the address of the server to connect to. If you want to connect to a replication set, specify multiple host addresses
  • PortX Specifies the port number. If this parameter is not specified, the default value is 27017
  • Database If username: pass@ is specified, connect to and verify the login to the specified database. If this parameter is not specified, the test database is opened by default
  • ? Options Connection options. If you do not use /database, you need to be preceded by a /. All join options are key-value pairs name=value, and key-value pairs are separated by & or; (semicolon) separated
options describe
replicaSet=name Verify the replica set name. Impliesconnect=replicaSet.
slaveOk=true|false True: In connect= Direct mode, the driver connects to the first machine, even if the server is not the master. In connect=replicaSet mode, the driver sends all write requests to the master and distributes read operations to other slave servers.

False: In connect= Direct mode, the driver automatically finds the primary server. In connect=replicaSet mode, the driver only connects to the primary server, and all read and write commands connect to the primary server.
safe=true|false True: After an update operation, the driver sends the getLastError command to ensure that the update is successful. (Also see wtimeoutMS).

False: After each update, the driver does not send getLastError to ensure that the update is successful
w=n The driver adds {w: n} to the getLastError command. Apply to safe = true
wtimeoutMS=ms The driver adds {wtimeout: ms} to the getLasterror command. Apply to safe = true
fsync=true|false True: The driver adds {fsync: true} to getLasterror. Apply to safe = true.

False: The driver is not added to the getLastError command.
journal=true|false If set to true, sync to journal (write to entity before committing to database). Apply to safe = true
connectTimeoutMS=ms The time at which the connection can be opened
socketTimeoutMS=ms The time to send and receive sockets

3 Using MongoDB in Java

Basic Java and MongoDB operations

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(a) {
        // No password mode
// mongoClientURI = new MongoClientURI("mongodb://localhost:27017/mycol");
        // There is password mode
        mongoClientURI = new MongoClientURI("mongodb://cf:123456@localhost:27017/mycol");
        mongoClient = new MongoClient(mongoClientURI);
        System.out.println(MongoClient object generation);
// // Connect to the mongodb service
// mongoClient = new MongoClient("localhost", 27017);

    }

    @After
    public void drop(a) {
        mongoClient.close();
        System.out.println(MongoClient object destruction);
    }

    // regular query
    @Test
    public void getByPattern(a) {
        // 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_insensitive); * Right matching: Pattern.compile("^.* Wang $", Pattern.case_insensitive); * Exact match: Pattern.compile("^ King $", Pattern.case_insensitive); * Fuzzy matching: Pattern.compile("^.* Wang.*$", pattern.case_insensitive); * /
        // Regular query: query all user names starting with king
        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()); }}// contains queries
    @Test
    public void getByInOrNin(a) {
        // Connect to mongodb service
        MongoClient mongoClient = new MongoClient("localhost".27017);
        MongoDatabase articledb = mongoClient.getDatabase("mycol");
        MongoCollection<Document> users = articledb.getCollection("test");

        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()); }}// Query statistics
    @Test
    public void getByCount(a) {
        // Connect to mongodb service
        MongoClient mongoClient = new MongoClient("localhost".27017);
        MongoDatabase articledb = mongoClient.getDatabase("mycol");
        MongoCollection<Document> users = articledb.getCollection("test");

        // Query statistics: check the number of people whose passwords are likes
        BasicDBObject filter = new BasicDBObject("likes".2);
        long count = users.countDocuments(filter);
        System.out.println(count);
    }

    // Sort queries
    @Test
    public void getByOrder(a) {
        // Connect to mongodb service
        MongoClient mongoClient = new MongoClient("localhost".27017);
        MongoDatabase articledb = mongoClient.getDatabase("mycol");
        MongoCollection<Document> users = articledb.getCollection("test");

        // Sort query: sort by 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(a) {
        // Connect to mongodb service
        MongoClient mongoClient = new MongoClient("localhost".27017);
        MongoDatabase articledb = mongoClient.getDatabase("mycol");
        MongoCollection<Document> users = articledb.getCollection("test");

        // Projection query: only _id and specified field information are displayed
        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(a) {
        // 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 query, query two 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(a) {
        // Connect to mongodb service
        MongoClient mongoClient = new MongoClient("localhost".27017);
        MongoDatabase articledb = mongoClient.getDatabase("mycol");
        MongoCollection<Document> users = articledb.getCollection("test");

        // Type query: Query information about all users whose user names are strings
        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(a) {
        // 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)));

        // Conditional query: likes user information 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()); }}// join query: AND query
    @Test
    public void getByANDCondition(a) {
        // 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)));

        // Conditional query: likes user information 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()); }}$ne, $gte, $lte, $gt, $lt
    // TODO equals TODO. Compare directly without adding operators (as follows)
    @Test
    public void getByCondition(a) {
        // Connect to mongodb service
        MongoClient mongoClient = new MongoClient("localhost".27017);

        // if articledb exists, return articledb, if not, create articledb
        MongoDatabase articledb = mongoClient.getDatabase("mycol");
        // If users exists, return users; if not, create users
        MongoCollection<Document> users = articledb.getCollection("test");
        // Query the information of users whose likes are not equal to 200
        BasicDBObject searchCond = new BasicDBObject();

        $ne $gte $lte $gt $lt
        searchCond.append("likes".new BasicDBObject("$ne".200));

        / / equal to
// searchCond.append("likes", 100);
        MongoCursor<Document> cursor = users.find(searchCond).iterator();
        while(cursor.hasNext()) { System.out.println(cursor.next()); }}// Delete documents, the first one that meets the condition/all documents that meet the condition
    @Test
    public void deleteDocument(a) {
        try {
            // Connect to mongodb service
            MongoClient mongoClient = new MongoClient("localhost".27017);

            // Connect to the database
            MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
            System.out.println("Connect to database successfully");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            System.out.println("Set test selected successfully");

            // deleteMany Deletes multiple entries
            // deleteOne Deletes a line
            // Delete the first document that meets the criteria
            collection.deleteOne(Filters.eq("likes".200));
            // Delete all documents that match the criteria
            collection.deleteMany(Filters.eq("likes".200));
            // retrieve the result
            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 the document
    @Test
    public void updateDocument(a) {
        try {
            // Connect to mongodb service
            MongoClient mongoClient = new MongoClient("localhost".27017);

            // Connect to the database
            MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
            System.out.println("Connect to database successfully");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            System.out.println("Set test selected successfully");

            // If we want to change only one field in the document, use the $set operator, otherwise the other fields will disappear
            // updateMany modifies all the conditions
            // updateOne Modifies the required item
            // Update the document. Change the document likes=100 to likes=200
            collection.updateMany(
                    Filters.eq("likes".100), new Document("$set".new Document("likes".200)));
            // retrieve the result
            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()); }}// Query the document
    @Test
    public void getDocument(a) {
        try {
            // Connect to mongodb service
            MongoClient mongoClient = new MongoClient("localhost".27017);

            // Connect to the database
            MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
            System.out.println("Connect to database successfully");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            System.out.println("Set test selected successfully");

            // Retrieve all documents
            /** * 1. 
      
        * 2. MongoCursor
       
         * 3. The collection of documents retrieved by cursor traversal * */
       
      
            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(a) {
        try {
            // Connect to mongodb service
            MongoClient mongoClient = new MongoClient("localhost".27017);

            // Connect to the database
            MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
            System.out.println("Connect to database successfully");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            System.out.println("Set test selected successfully");
            // Insert the document
            /** * 1. Create org.bson.Document with key-value * 2. Create a Document collection List < Document > * 3. Insert the Document collection database collection mongoCollection. InsertMany (List < Document >) can be used to insert a single Document mongoCollection.insertOne(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 the collection
    @Test
    public void getCollection(a) {
        try {
            // Connect to mongodb service
            MongoClient mongoClient = new MongoClient("localhost".27017);

            // Connect to the database
            MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
            System.out.println("Connect to database successfully");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");
            System.out.println("Set test selected successfully");
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ":"+ e.getMessage()); }}// Create a collection
    @Test
    public void createCollection(a) {
        try {
            // Connect to mongodb service
            MongoClient mongoClient = new MongoClient("localhost".27017);

            // Connect to the 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()); }}// Connect to service 2
    @Test
    public void test2(a) {
        try {
            // If remote connections are used to connect to the MongoDB service, replace localhost with the SERVER IP address
            //ServerAddress() two parameters are ServerAddress and port respectively
            ServerAddress serverAddress = new ServerAddress("localhost".27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);

            / / MongoCredential createScramSha1Credential () three parameters of user name password database name respectively
            MongoCredential credential = MongoCredential
                    .createScramSha1Credential("username"."databaseName"."password".toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);

            // Obtain the MongoDB connection through connection authentication
            MongoClient mongoClient = new MongoClient(addrs, credentials);

            // Connect to the database
            MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
            System.out.println("Connect to database successfully");
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ":"+ e.getMessage()); }}// Connect to service 1
    @Test
    public void test1(a) {
        // Connect to mongodb service
        MongoClient mongoClient = new MongoClient("localhost".27017);

        // Connect to the database
        MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
        System.out.println("Connect to database successfully"); }}Copy the code