Recently, due to the needs of the new game business, I decided to abandon mysql and embrace mongodb, so I decided to talk to mongodb myself to see if there is really any value worth using.

Mongodb walked out from the office area, high and thin a young man, this thought should be a small fat, after all mango is not fat fat.

Hello, are you Mango DB? I was the first to say hello.

Yes, but I’m not called Mango DB, I’m called mongodb, my original name comes from the English word “Humongous”, meaning huge, people like its name, it means I have the ability to deal with large-scale data.

I asked aunt mysql earlier, she said that you are different from her, she is better at dealing with relational data, you are more rational, better at dealing with non-relational data, and claimed to be a document database, I would like to ask if there is any difference between your two responsibilities?

First, let me explain what a document database is. A document is the basic unit of data, and the ordering of multiple key-value pairs together is called a document. Maybe you don’t understand this, but look at this chart

The simple explanation is that the document corresponds to rows in the database.

As for the duty on actually like aunt mysql description, we are dealing with relational one, one is processing non-relational, is complementary, for your users, because if the needs of the business or project is the initial stage, and lead to specific data format cannot be clearly defined, best use mongo, compared with the relational database, We are very easy to extend, which makes writing code very convenient.

We have nothing to do with the game data itself, but our project team is familiar with Mysql. After all, we often cooperate with each other. This is the first time to know about mongodb.

I can see that you are new to mysql haha, don’t worry, because aunt mysql is very well designed and widely used, so my dad Dwight Merriman also strictly referred to the conceptual model of mysql at the beginning of the design, after all, it is important to learn from the predecessors, so many people say, Mongodb is the most mysql like database in NoSQL, as you can see from this table

Basically is changed a method just, as to have what difference, I let them oneself come out and you explain.

Mongodb say that finish, then ran out of a few younger brother, the original mongodb or a small team ah, just and I talk about the original captain, mainly responsible for sales, each in its own place, exquisite ah.

First, a guy named Database spoke up. He said he had the same concept as mysql’s database, that a database contains multiple sets (tables). Then he smiled and walked away.

A collection can hold multiple files (rows), but the difference is that the schema of the collection is dynamic, and there is no need to declare a strict table structure.

A document is the equivalent of a ROW, a document is composed of multiple fields and is represented in BSON format, and a document is the equivalent of a COLUMN in SQL. The difference between columns is that field types can be more flexible, such as supporting nested documents and arrays.

My brother said that he had drawn a table for me, saying it was the comparison of fields.

After listening to the speeches of several young men, I was amazed at how exquisite the design is and how friendly it is to beginners. But I just heard a relatively new thing, what is bson?

Mongodb captain shouted, Bson come out, tell me what you are.

Mongodb captain say that finish, present all laughed ha ha ha ha.

Bson heard someone call him and ran out.

Well, a very handsome young man.

According to Bson, MongoDB documents are jSON-based in format, and typically look like this:

{
  "_id": 1."name" : { "first" : "John"."last" : "Backus" },
  "contribs" : [ "Fortran"."ALGOL"."Backus-Naur Form"."FP"]."awards": [{"award" : "W.W. McDowell Award"."year" : 1967."by" : "IEEE Computer Society"
    }, {
      "award" : "Draper Prize"."year" : 1993."by" : "National Academy of Engineering"}}]Copy the code

At one time, the advent and popularity of JSON made data transfer in Web 2.0 very easy, so using JSON syntax was very easy for developers to accept. JSON has its own drawbacks, such as not being able to support specific data types like dates, so MongoDB actually uses an extended JSON called BSON(Binary JSON), which supports a variety of structure types. In short, I’m an updated version of JSON. I’ll show you the data types I support

How does mongodb handle high concurrency in a distributed environment with unique ids? When we were researching mysql distributed applications, we found that mysql was not handled, which was a pain in the ass.

In most relational databases such as mysql, the primary key is increditable. However, in a distributed environment, it can easily conflict. For this reason, we have adopted a type called ObjectId as the primary key. ObjectId is a 12-byte string of type BSON. Each primary key consists of four parts:

  • 4 bytes: UNIX timestamp
  • 3 bytes: indicates the machine running MongoDB
  • 2 bytes: indicates the process that generated this _id
  • 3 bytes: The value generated by a counter starting with a random number

The first three parts ensure that every second each Mongo process produces a different document ID, and then each Mongo process maintains its own counter, so the same process will have different documents every second, but there will be a upper limit, which is related to the number of bits of the counter. In this way, uniqueness is guaranteed within the same set.

Well, indeed, through these four parts, it’s almost unique.

I am satisfied, mongodb captain continued to add, in the operation syntax, you must have considered whether it is relatively smooth to use, rest assured, our data operation command is also based on JSON/BSON format, basically there is no learning cost, to give you some examples

For example, inserting a document:

Perform document lookup:

Delete document:

In traditional SQL syntax, it is possible to limit the returned fields, and MongoDB can use Projection to represent them:

As you can see, the BSON/ JSON-based syntax isn’t that complicated, and it’s even more expressive than SQL.

Well, it is really silky, our project team should like it very much, suddenly thought subcutaneous, then if we want to use SQL statement to query something, ok?

Mongodb captain smiled, of course, it is possible, but it needs to be realized by third-party tool platforms. You are the server, you can look at some platforms like Presto, and if you are the client, you can consider using tools like MongoBooster and Studio3t.

By the way, what about indexing? In mysql, we’ve been doing this for a long time. Will we switch to mongodb and start all over again?

Hey hey hey mongodb laughed again, as if guessing what I was going to ask. No.

First, the technical implementation of indexing relies on the underlying storage engine, currently we use wiredTiger as the default engine. The engine uses a B+ tree structure for index implementation, which is no different from other traditional databases, meaning that some of the index tuning techniques of most SQL databases are still available on MongoDB.

Wow, that’s great. How do you create an index?

Don’t worry, let me give you a few examples. Mongodb uses ensureIndexes to declare a plain index for a collection

db.book.ensureIndex({author: 1})
Copy the code

What does the number after author mean? It should make sense that 1 is ascending, or -1 if it’s descending.

So how do you implement compound indexing? We can look at

db.book.ensureIndex({type: 1, published: 1})
Copy the code

But it is only for compound indexes that the order of the index keys becomes meaningful.

See, it’s pretty simple. It’s pretty clear.

In addition, mongodb supports the following indexes:

  • HASH index. HASH is another data structure for quick retrieval, and HASH sharding keys of MongoDB use HASH indexes.
  • Geospatial index, used to support fast geospatial queries, such as finding businesses within 1 km.
  • Text index, used to support fast full text search
  • Wildcard Index, a flexible Index based on matching rules, was introduced in version 4.2.

It seems that mysql also does not have these index types.

Sure, I’ve never heard of geospatial indexes before, of course, maybe I haven’t used them, but what about the features of indexes?

Yes, you can set parameters to give index properties, such as

  • Unique =true, indicating a unique index
  • ExpireAfterSeconds =3600, indicating that this is a TTL index and the data will age after 1 hour
  • Sparse =true, indicating a sparse index that indexes only documents with non-null fields
  • PartialFilterExpression: {rating: {$gt: 5}, conditional index, that is, only the documents that meet the calculation conditions are indexed

Good ah, basically the same, learning cost is really low ah, that is not the index evaluation of the use of explain ah.

On the other hand, the explain() command can be used for query plan analysis to further evaluate the effectiveness of indexes, for example

You can see from the results whether the execution plan is efficient, for example, if the result of missing the index, COLLSCAN is displayed, if the result of hitting the index, IXSCAN is used, memory SORT is displayed, and the developer can use the result to tune.

Ah ah ah, very good very good, for our group of mysql to mongodb, basically no learning cost ah, in addition, you recommend basic books to me, you recommend, we are also more assured.

No problem, Noh. We’re collecting information on this, too

Not bad, if you need to help yourself, click the link

Ok, well, why don’t you come and share with our project team? Our partner wants to hear about the design of high availability.

Ok, let’s make an appointment later and we’ll talk more about it then.

The mysql related, interested friends can see zhuanlan.zhihu.com/p/404685504

This article write of more serious, helpful words, beg each friend dot praise + like + collect support below! ❤ ️

I am porridge snow, continue to share programming dry goods, behind the high availability of this piece of time and I make an appointment with mongodb captain, we will see each other.