Sometimes I have to feel that the system upgrade is really a lot of benefits, not only gave me a chance to reconstruct the bad code before, but also satisfied my vanity of active learning. Redis got started, Elasticsearch got started, and MongoDB got started again. I feel bald and powerful at the same time.

Before I read further, I should note that I have not done much research into MongoDB, but only to learn how to use it. But as a responsible tech blogger, I put a lot of thought into it, and this tutorial will be so satisfying that you can’t help liking it.

Of course, friends encounter mistakes in the article, don’t be lenient, can group to beat me, but make sure that one point, don’t hit the face, I am afraid of disfigurement.

What is MongoDB

MongoDB is a distributed file storage database designed to provide scalable high-performance data storage solutions for Web applications.

The above quotes are official and, it must be said, well explained. MongoDB stores data as a document (similar to a JSON object). The data structure consists of key-value pairs (similar to a Map in Java). Access by keys is much more efficient, right? This is the most important feature of MongoDB.

MongoDB offers both an enterprise (more powerful) and a community edition, which is enough for us developers to learn and use. MongoDB has many driver packages, which are covered by common programming languages, such as Java, JavaScript, C++, C#, Python and so on.

MongoDB is used by many well-known Internet companies, such as Google, Facebook, eBay, etc. In short, worthy of trust, small partners rest assured that the entry, technology is not pressure ah, when it is to give yourself a learning opportunity.

02. Install MongoDB

MongoDB has different installation packages for different operating systems, so for this introductory article we’ll use Windows as an example.

The official website download address is as follows:

www.mongodb.com/download-ce…

The latest version is 4.2.6. I chose the installed version, in MSI format, around 264M. Once you’ve downloaded it, you can double click to start the installation, dumb-ass.

You are advised to select Custom to customize the installation, as shown in the following figure.

Run in service mode and configure the data and log directories as shown in the following figure.

It is recommended that you uncheck the graphical client tool for installing MongoDB, otherwise the installation will slow down to the point where you want to lock your phone.

After the installation, go to the bin directory and double-click mongo.exe to connect to the MongoDB service.

1) The default MongoDB port number is 27017.

2) The MongoDB version is 4.2.6.

The default connection is to the test document (equivalent to data), which can be queried using the db command.

You can also run some simple arithmetic operations:

So how do you stop service? You can directly click on the top right corner of the X – rough, wall dong.

03. Install Robo 3T

With support for MongoDB and SCram-SHA-256 (upgraded Mongo shell), Robo 3T is a lightweight MongoDB client tool.

Download address:

robomongo.org/download

The latest version is 1.3, select zip format for download, about 23M. Once the download is complete, unzip it.

The package directory is not explained one by one. Go to the bin directory and double-click robo3t.exe to start the Robo 3T client.

Click “Create” to Create a MongoDB connection.

Once the connection is successful, you can operate MongoDB.

(However, you may not know how to use MongoDB at this time, after all, some related concepts are not clear, do not know how to start.)

04. Concepts related to MongoDB

With the rapid development of the Internet, user data is becoming larger and larger. The development of NoSQL database can deal with these large data well. MongoDB is a typical representative of NoSQL database.

For those of you who don’t know what NoSQL stands for, let me explain. No is Not the meaning of SQL, SQL, it actually means Not Only is “is Not Only the SQL”, refers to is a relational database, and the traditional relational database MySQL, Oracle, different.

The name comes from the English word humongous, which means “enormous”, illustrating MongoDB’s ambition. MongoDB data is stored in jSON-like binary documents:

{
    name: "Silent King II.",
    age: 18,
    hobbies: ["Writing"."Knock code"]}Copy the code

Before moving on, you need to understand a few key concepts in MongoDB, such as what a collection is, what a document is, what a field is, and so on. MongoDB is very similar to a relational database, although it is non-relational.

After looking at the picture above (from macroZheng’s article), is it immediately clear?

Use MongoDB in Java

Some of you might ask, “Dude, I’m a Java programmer. How do I use MongoDB in Java?” That’s a good question. I’m on my way. I’m on my way.

First, add MongoDB driver dependencies to your project:

< the dependency > < groupId > org. Mongo < / groupId > < artifactId > mongo - driver - sync < / artifactId > < version > 4.0.3 < / version > </dependency>Copy the code

MongoDBTest step 2 create a new test class:

public class MongoDBTest {
    public static void main(String[] args) {
        MongoClient mongoClient = MongoClients.create();
        MongoDatabase database = mongoClient.getDatabase("mydb");
        MongoCollection<Document> collection = database.getCollection("test");

        Document doc = new Document("name"."Silent King II.")
                .append("age"."18")
                .append("hobbies", Arrays.asList("Writing"."Knock code"));
        collection.insertOne(doc);

        System.out.println("Set size:" +collection.countDocuments());

        Document myDoc = collection.find().first();
        System.out.println("Document Content:"+ myDoc.toJson()); }}Copy the code

MongoClient: MongoClient client connection object for MongoDB. If host name and port number are not specified, the default is’ localhost ‘and’ 27017 ‘.

If you want to customize the host name and port number, you can use a string:

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
Copy the code

Does this feel like a MySQL connection string?

MongoDatabase () : MongoDatabase (MongoDatabase) : MongoDatabase (MongoDatabase); MongoDatabase (MongoDatabase) : MongoDatabase (MongoDatabase);

3) The getCollection() method is used to get the Document object with the specified name. If the Document already exists, it returns the collection object of the Document directly, otherwise it creates a collection object and returns it (similar to getDatabase()).

With the MongoCollection document object in place, you can now add concrete document content to it.

 Document doc = new Document("name"."Silent King II.")
                .append("age"."18")
                .append("hobbies", Arrays.asList("Writing"."Knock code"));
Copy the code

The Document object comes from the org.bson package and can be instantiated by adding the corresponding key-value pair via the append() method, just like the Append () method of the String class.

Once you have the document object, you can add the document to the collection using the insertOne() method.

4) The countDocuments() method is used to get the number of documents in the collection.

5) To query documents, use the find() method, which returns a FindIterable object, and the first() method, which returns the first document object in the current collection.

Ok, let’s look at the output of the program:

Set size: 1 document content: {"_id": {"$oid": "5ebcaa76465cab3f18b93e1a"}, "name": "Silent King II."."age": "18"."hobbies": ["Writing"."Knock code"]}
Copy the code

Exactly what we expected, Perfect!

You can also view the “myDB” database using Robo 3T, as shown in the figure below.

06, thanks

Ok, my dear friends, the above is the content of this article, if you want to practice MongoDB after reading, hurry up! If you have any problems in the process of learning, please feel free to communicate with me. Although I am a rookie, I am enthusiastic.

Also, if you want to write an entry level article, this is the perfect example.

I am silent King 2, an interesting programmer. If you think this article is helpful to you, please search “Silent King ii” on wechat and read it for the first time. Reply [666] there is also a 500G HIGH-DEFINITION teaching video (classified) that I prepared for you.

Interview on GitHub

Original is not easy, do not want a free ticket, please point a praise for this article, it will be the strongest power FOR me to write more high-quality articles.