Mongdb learning notes (I) first encounter

Time:2022-6-20

I went to see my high school classmates this week. I was very happy. I originally intended to write articles about the implementation of MySQL database transactions or MySQL optimization series, but I haven’t thought about how to assemble these knowledge.

Just change direction this week and write NoSQL. Considering that some students don’t know much about JSON, here we first introduce the basic concept of mongdb, then explain why mongdb should be introduced, and then explain how to use it.

What is it? what

Mongodb is a document database designed for ease of application development and scaling

Mongdb is a document database designed for high scalability and high availability.

Note that mongdb is a document database. What is the difference between a document database and a common relational database? Let’s first look at this document, that is, what does document mean?

A record in mongodb is a document, which is a data structure composed of fields and value pairs. Mongodb documents are similar to JSON objects. Field values can include other documents, arrays, and document arrays.

Mongdb learning notes (I) first encounter

About what is JSON? See my article: silly JSON?

So the record of mongdb is a document similar to a JSON object. Mongdb stores the document in a collection, which is similar to a table in a relational database. The access relationship is similar to the following figure:

Mongdb learning notes (I) first encounter

We mentioned above that mongdb’s record is a JSON like document. The reason why it is similar to is that mongdb adopts bson. Bson = Binary JSON, that is, JSON in binary form. At the same time, it expands JSON and has data types that are not available in JSON, such as date type and bindata type.

Why introduce mongdb?

So why introduce mongdb? Or what are the advantages of mongdb over relational databases?

Ten years ago, when Dwight and I started this project, which later became mongodb, we never thought it would look like today. We have only one belief: make developers more efficient. Mongodb was born out of the frustration of using relational databases in large and complex business deployments. We set about building a database we wanted to use. In this way, whenever developers want to write an application, they can focus on the application itself instead of around the database. Ten years of mongodb, review of a founder

So in some areas, mongdb can make developers more efficient.

It seems that there is a problem: what are the advantages, disadvantages and applicable scenarios of NoSQL such as mongodb compared with relational databases? The following is an answer from a mongdb developer. Here I will briefly extract his answer:

  • The document (JSON) model is more similar and natural to the object-oriented data representation. Unlike table structures in relational databases, arrays and subdocuments (JSON) can be embedded in documents (JSON), just like arrays and member variables in programs. This is not allowed for the three normal forms of relational databases. But in practice, we often see one to many and one to one data. For example, the tag list of a blog post is very intuitive as a part of the post, but it is not natural to put the dependency between tag and the post in a separate table. SQL speech can be accurately formulated. However, the three paradigms emphasize that there is no redundancy in the data, which is not the most concerned problem of programmers today. The more important problem is whether they are convenient to use.

Here we come to the first advantage of mongdb over relational databases. In some scenarios, mongdb is more convenient than relational databases. Note that in some scenarios.

  • performance

    Jojn brought about by the three paradigms sometimes has to join multiple tables to meet a query, but the cost of joining multiple tables is that with the improvement of data, the query speed will become very slow. A simpler access mode can make it easier for developers to understand the performance of the database. A typical scenario is that I join ten tables. In this case, how can I add indexes to obtain the optimal query speed.

  • flexible

    If you need to add fields, you may need to change them from the database to the application layer. Although some tools can automate it, it is still a complex task. Without a schema, mongdb does not need to change the database. It only needs to make necessary changes in the application layer. (this sentence can be understood as follows. Look carefully at the diagram of mongdb accessing data drawn above. The students accessing the collection now have three fields. In fact, mongdb allows documents to have different fields.)

Custom attributes are also a problem. For example, the product features of LCD display and LED display are different. This feature of data is called polymorphism. How should the product table be designed in a relational database? Generally speaking, the simplest solution is to turn each possible attribute into a separate column. However, if the display manufacturer introduces a new feature every year, the table will need to be changed frequently and the scalability is not strong. Another more extreme scenario is that an address book allows users to add new contact information at will. One solution is to put this custom contact information in one column and store it in JSON.

The flexibility of mongdb is also reflected in unstructured and semi-structured data. Mongdb provides full-text indexing and also supports geographic location query and indexing. For example, a user wants to know where there is a public toilet within a radius of five kilometers. This is “geographical range query”. Then he searched for the nearest bike. Moby bike uses mongodb to complete such “distance Sorting Query”. It is strongly recommended to use the geographic location index to speed up the query, because I can understand the user’s mood.

  • Scalability

    Mongdb has its own partitions, which correspond to the database and table partitions of the relational database.

  • Which scenarios are not suitable for mongdb

Zhousiyuan, the developer of mongdb, gave a scenario. He needed a subway train timetable in a project. The official data provided was a SQL format that met the industry standard, that is, it was divided into several tables according to the three paradigms. Then he spent the night importing the database into mongdb. But he said that if he did it again, he might directly select the relational database, because if the source data format is SQL data, it can not be controlled, and the amount of data is small; With rich cross reference relationships, rich query patterns, and applications that do not require high performance, relational data pages are also a pragmatic choice.

My understanding of this sentence is that from the perspective of modeling application data, in some scenarios, SQL provided by relational databases still has strong advantages in statistics, query and analysis.

How to use it?

After we have what and why, we can start to use them, that is, to install and use them. Fortunately, mongdb has a Chinese operation manual maintained by Chinese people:

Mongdb learning notes (I) first encounter

The introduction is quite detailed. There are also installation tutorials and free trials:

Mongdb learning notes (I) first encounter

So for me, I chose the interview and trial. Click here. The development scenario I chose is to develop micro services. You can also choose to install them locally. The installation tutorial in this manual is quite detailed. I will put an address here instead of making a detailed introduction.https://docs.mongoing.com/ins…

However, for databases in the cloud, it may be a little more troublesome to install the mongdb shell. I have been installing it on windows for a long time, but it has not been successful. Here you can use the mongdb GUI. The download address is as follows:

https://downloads.mongodb.com…

Mongdb learning notes (I) first encounter

Mongdb learning notes (I) first encounter

Just fill in JSON

Java manipulation mongdb

Now let’s try to use it. What I talked about in the first encounter article is some basic features, such as crud. First of all, the connection to the database must be driven:

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

Adding, deleting, modifying, and querying. The basic steps in dealing with databases are generally to obtain connections and then send statements. In the Java driver of mongdb, adding, deleting, modifying, and querying are related to document and bson:

Mongdb learning notes (I) first encounter

Mongdb learning notes (I) first encounter

When we add a new object, it is a new document, like a lost value. Filter is used to construct condition objects for querying:

Filters. NE is not equal to
Filters. GT greater than
Filters. and(Filters.eq("age",2222)),Filters. EQ ("name", "AAA") is equal to
Filters. GTE greater than or equal to
Filters. LT less than
Filters. LTE less than or equal to
Filters.in()
Filters.nin() not in

In essence, filters are used to help you pass operators. We can also achieve the same effect with the help of document:

New document ("name", "Zhang San") = filters EQ ("name", "Zhang San")
 new Document("age",new Document("$eq",24))  = Filters. EQ ("name", "Zhang San")
 new Document("age",new Document("$ne",24))  = Filters. Ne ("name", "Zhang San")

We mainly use mongocollection to complete the addition, deletion, query and modification of mongdb. The addition is mainly related to document. Modifying, deleting, and querying can be implemented using filters and documents.

  • increase
@Test
void contextLoads() throws Exception {
    ConnectionString connectionString = new ConnectionString("mongodb+srv://study:[email protected]/myFirstDatabase?retryWrites=true&w=majority");
    MongoClientSettings settings = MongoClientSettings.builder()
            .applyConnectionString(connectionString)
            .build();
    MongoClient mongoClient = MongoClients.create(settings);
    insertDocumentDemo(mongoClient);
}

public void insertDocumentDemo(MongoClient mongoClient) throws  Exception {
    MongoDatabase database = mongoClient.getDatabase("test");
    database.getCollection("study");
    MongoCollection<Document> study = database.getCollection("study");
    //Number name ID is stored in the study table. If it is a relational database, we need to add fields in the table to add attributes,
    //Now in mongdb, we directly add
    Map<String,Object> map = new HashMap<>();
    map.put("number","bbb");
    map.put("name","aaa");
    map.put("id","1111");
    map.put("age",2222);
    Document document = new Document(map);
    study.insertOne(document);
}

result:Mongdb learning notes (I) first encounter

  • Delete
public void deleteDocument(MongoClient mongoClient){
        MongoDatabase database = mongoClient.getDatabase("test");
        database.getCollection("study");
        MongoCollection<Document> study = database.getCollection("study");
        //EQ is the equals operator, filters EQ ("age", 2222) indicates that the object with age = 2222 is detected and located
        study.deleteOne(Filters.eq("age",2222));
}
  • change

    public void updateDocument(MongoClient mongoClient){
            MongoDatabase database = mongoClient.getDatabase("test");
            database.getCollection("study");
            MongoCollection<Document> study = database.getCollection("study");
            study.updateOne(Filters.eq("age",2222),new Document("$set",new Document("name","22222")));
     }
  • check
public void selectDocument(MongoClient mongoClient){
        MongoDatabase dataBase = mongoClient.getDatabase("test");
        MongoCollection<Document> studyTable = dataBase.getCollection("study");
        //Age can be an array, and all values must be 2222
        Bson condition = Filters.all("age", 2222);
        FindIterable<Document> documentList = studyTable.find(condition);
}

Finally, to sum up

Mongdb learning notes (I) first encounter

To some extent, we all take data from real data, send it to the database after processing, and then take out the data in the database according to the user’s request. However, the data structures in the real world are diverse, and the relational database is powerful. For example, we discussed above why we introduced mongdb. Another scenario is to describe the relationship between data, such as organizational structure, When the amount of data is large, the relational database is faced with the problem of slow query speed. In order to describe this nonlinear relationship, the graph database came into being. Different databases are responding to different data description scenarios.

reference material

Recommended Today

JQuery obtaining form data and data submission (I)

HTML <form id=”form-box”> … </form> JQuery get form data JQuery to get form data: let json = $(‘#form-box’).serialize(); console. log(‘json: ‘, json); // Output: json:name=w3h5&type=web Object format: let data = {}; let value = $(‘#form-box’).serializeArray(); $.each(value, function (index, item) { data[item.name] = item.value; }); let json = JSON.stringify(data); console.log(json); /* *Output: {“name”: “ASD”, “type”: “1”} […]