I was happy to see my high school friends this week. I originally intended to write a series of articles on implementing MySQL database transactions or MySQL optimization, but I haven’t figured out how to assemble this knowledge yet.

Just switch gears this week and write about NOSQL. Considering that some students are not familiar with MongDB, here we introduce the basic concept of MongDB first, then explain why MongDB is introduced, and then explain how to use it.

What is? what

MongoDB is a document database designed for ease of application development and scaling “MongDB官网”

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

Note that MongDB is a document database, what’s the difference between a document database and a relational database? So let’s first look at this document, what does document really mean?

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

What is JSON? See my article: JSON stupid can’t figure out?

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:

As mentioned above, the record of MongDB is a document similar to JSON. The reason why it is similar is that MongDB adopts BSON, BSON = Binary JSON, that is, JSON in Binary form, but at the same time, it has expanded JSON and has data types that are not available in JSON. Such as Date type, BinData type.

Why MongDB?

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

Ten years ago, when Dwight and I started the project that would become MongoDB, we could never have imagined what it would become today. We believe in one thing: making developers more productive. MongoDB was born out of the frustration of using relational databases in large, complex business deployments. We set out to build a database that we wanted to use ourselves. That way, whenever developers want to write an application, they can focus on the application itself, not the database. MongoDB’s Decade: A Founder’s Look back

So there are certain areas where MongDB makes developers more efficient.

Zhihu has a question: what are the advantages and disadvantages and application scenarios of NoSQL such as MongoDB compared with relational databases? Here is an answer from one of MongDB’s developers. Here is a brief excerpt of his answer:

  • The document (JSON) model is more similar and natural to 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 by the relational database triple paradigm. But in practice we often see one-to-many and one-to-one data. For example, a list of tags for a blog post is intuitive as part of the post, but putting tags and article affiliations in a separate table is less natural. SQL speech can be formalized with great precision. However, the fact that the three paradigms emphasize that data does not have any redundancy is not the most important issue for today’s programmers, but rather how easy it is for them to use.

So here we have the first advantage of MongDB over relational databases, that in some cases MongDB is more convenient than relational databases, but in some cases.

  • performance

    Three paradigms of jojn, sometimes in order to satisfy a query, had to join multiple tables, but the price of the join table more is up the data, query speed will be slow, more simple access mode allows developers to more easily understand the performance of the database, an example of a typical scenario is that I join the ten tables, In this case, how can I add index to get the optimal pair of query speed.

  • flexible

    If you need to add a field, you may need to change it all the way from the database to the application layer, and although some tools can automate it, it’s still a complex task. MongDB does not have a Schema, so you do not need to change the database, only need to make necessary changes in the application layer. If you look at the picture of MongDB accessing data, all 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, LCD displays and LED displays have different product characteristics. Such characteristics of data are called polymorphisms. The simplest solution is to make each possible attribute a separate column, but if the display manufacturer releases a new feature every year, the table changes frequently and does not scale well. In a more extreme scenario, an address book allows users to add new contact information at will. One option is to put this custom contact information in a column and store it in JSON.

The flexibility of MongDB is also reflected in unstructured and semi-structured data. MongDB provides full-text index, and also supports geographical location query and index. For example, a user wants to know where there is a public restroom within a radius of five kilometers. This is a “geographic range query.” Then he searched for the nearest bike. Mobike uses MongoDB to complete such “distance sorting queries”. I strongly recommend using a geolocation index to speed up queries, as I can understand this user’s feelings.

  • scalability

    MongDB native fragments, corresponding to relational database sub-database sub-table.

  • In what scenarios is MongDB not suitable

MongDB’s developer, Zhou Siyuan, cites a scenario in which he needed a subway train schedule for a project. The official data was provided in an industry-standard SQL format, which is divided into several tables according to three paradises. He then spent the night importing the database into the MongDB. But he said that if he were to do it again, he would probably go straight to a relational database, because if the source data format is SQL data, there is no control over the amount of data; With rich cross-reference relationships, rich query patterns, and applications that don’t require high performance, relational data pages are also a pragmatic choice.

In some scenarios, SQL provided by relational databases still has a powerful advantage in terms of statistics, queries, and analysis.

How does it work?

With what and why, we can start to use it, that is, to install and use it. Fortunately, MongDB has a Chinese operation manual maintained by MongDB:

The introduction is quite detailed, there are also installation tutorials, as well as free trials:

So for me, I chose the interview trial, click in, I choose the development scenario is the development of micro services, you can also choose to install in the local, this manual on the installation of the tutorial is quite detailed, here I will put an address, not to do a detailed introduction. Docs.mongoing.com/install-mon…

However, for this kind of database in cloud, installing shell with MongDB may be a little bit more troublesome. I have been installing shell with MongDB on Windows for a long time, but it is not successful. Here you can use GUI of MongDB, download address is as follows:

Downloads.mongodb.com/compass/mon…

You can fill in JSON

Java manipulation MongDB

Now let’s try it out. I talked about some basic features in the introduction, CRUD and so on. To connect to the database first, you definitely need a driver:

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

Add, delete, change and search, the basic step of dealing with the database is to get the connection, and then send the statement. In the Java driver of MongDB, add, delete, change and search are related to the Document and Bson classes:

When we add objects, it’s new Document, like dropping values inside. Filter is used to construct conditional objects for query:

Filters. Ne is not equal to Filters. Gt greater than Filters."age".2222)),Filters.eq("name"."aaa"Light is less than Filters. Lte is less than or equal to Filters. In () filters.nin () not inCopy the code

The Filters are essentially passing operators for you, and we can do the same with Document:

 new Document("name"."Zhang") = Filters.eq("name"."Zhang")
 new Document("age".new Document("$eq".24))  = Filters.eq("name"."Zhang")
 new Document("age".new Document("$ne".24))  = Filters.ne("name"."Zhang")    
Copy the code

We mainly use MongoCollection to complete the addition, deletion, review and modification of MongDB, and the addition is mainly related to Document. You can do this using Filters and documents.

  • increase
@Test
void contextLoads(a) 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");
    // select * from 'study' where 'number name' = 'id';
    // Now in MongDB we add it directly
    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);
}
Copy the code

Results:

  • delete
public void deleteDocument(MongoClient mongoClient){
        MongoDatabase database = mongoClient.getDatabase("test");
        database.getCollection("study");
        MongoCollection<Document> study = database.getCollection("study");
        Eq ("age",2222) Filters. Eq ("age",2222) finds objects where age = 2222
        study.deleteOne(Filters.eq("age".2222));
}
Copy the code
  • 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")));
     }
    Copy the code
  • check

public void selectDocument(MongoClient mongoClient){
        MongoDatabase dataBase = mongoClient.getDatabase("test");
        MongoCollection<Document> studyTable = dataBase.getCollection("study");
        // Age can be an array, all values must be 2222
        Bson condition = Filters.all("age".2222);
        FindIterable<Document> documentList = studyTable.find(condition);
}
Copy the code

So just to conclude

To some extent, the extent to which we are derived from real data to the data after processing into database, and then according to user’s request to take out data in the database, but in the real world data structure is mixed, relational database and powerful cannot catch scene, as we discussed in the above why introduce MongDB, Another scenario is to describe the relationship between data, such as organizational structure and interpersonal graph. When there is a large amount of data, relational database will face the problem of slow query speed. In order to describe this nonlinear relationship, graph database emerged at the historic moment. Different databases deal with different data description scenarios.

The resources

  • Chinese version docs.mongoing.com/ directing Chinese manual | official document

  • What are the advantages and disadvantages and application scenarios of NoSQL such as MongoDB compared with relational databases? www.zhihu.com/question/20…

  • BSON website bsonspec.org/#/

  • Java mongodb — query data www.cnblogs.com/simple-ly/p…