Last set of courses taught Koa2, challenge full stack must deal with the database, personally feel as a front-end developer, operating MongoDB or more comfortable. Because it is a NoSql database, there is no NEED to write SQL statements, and the usage is in the form of JSON objects. Therefore, we checked the MongoDB course in the middle of Koa2 courses. After operating the database, we will go back to learn Koa2 database connection and operation. Finally, the technical fat will lead us to do a little actual combat.

This is the latest MongoDB release, now version 3.6.

Note: Every week, 2-3 classes are updated, each class is about 12 minutes, because I think I can only keep the attention of 12-15 minutes each class (generally get up at 4 in the morning, start to update, more stupid than others to work harder than others), in the form of video and pictures to update.

Fat technology is not a full-time lecturer, or a front-line programmer, so there are inevitably mistakes and mistakes in the course, I hope friends point out in the message, let us make progress together. The course references the Authoritative MongoDB Guide, 2nd edition.

Get hd offline video, leave your email and it will be sent to you for free.

Your name (required)

Your email address (required)

Section 01: Get to know and install MongoDB

We all know that MongoDB is a non-relational database. To understand non-relational database, we must first understand relational database. Relational database is a database built on the basis of relational model. More well-known relational databases, such as Oracle, DB2, MSSQL, Mysql.

What is the difference between a non-relational database and a relational database?

  • Essence: the essence of non-relational database: non-relational database product is the traditional relational database function castrated version, by reducing the use of less or less used functions, to greatly improve product performance.
  • Price: At present, non-relational databases are basically free, while more famous relational databases are charged, such as: Oracle, DB2, MSSQL. MySql is free, but handling large data requires a lot of work in advance.
  • Function: in the actual development, many business requirements, in fact, do not need a complete relational database function, non-relational database function is enough to use. In this case, it is certainly wise to use a non-relational database with higher performance and lower cost.

After understanding the difference between relational database and non-relational database, there is a bit of choice. Non-relational database is not recommended for complex and large projects, but if you want to make a blog, CMS system, such as business logic is not complex program, MongoDB is fully capable.

Directing a summary:

MongoDB is a database based on distributed file storage, written by C++ language. The goal is to provide scalable high-performance data storage solutions for WEB applications. MongoDB is a product between relational database and non-relational database, non-relational database has the most rich function, the most like relational database. The data structure it supports is very loose, in jSON-like Bson format, so it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is somewhat similar to object-oriented query language. It can almost achieve most of the functions similar to single table query of relational database, and it also supports data indexing.

 

Install the mongo:

MongoDB installation is divided into Windows installation and Mac installation (Liunx and Mac are similar). We’ll just cover Windows installations (don’t ask me why, as you all know, I don’t own a Mac).

Installation steps:

  1. Go to the official website to Download MongoDB, www.mongodb.com/, and find the Download button. Download can be a little busy, foreign servers, you know.
  2. Download and install. It is not difficult to install, but it is recommended for beginners to choose the default installation rather than their own configuration. We’ll wait until we’re fully familiar with the custom configuration.
  3. If there is safety software when installation, can report a few intercept, uniform allow good, do not allow can install failure.
  4. After the installation is complete, you need to configure environment variables so that they can be used directly on the command line without entering a long path. (Watch the video for this step)

Run the MongoDB server:

After installing the MongoDB database, we need to enable the server to use it. The command to enable the service is: Mongod.

  1. Open the CLI: First open run (win+R), then enter CMD and press Enter to open the CLI tool.
  2. Execute mongod: Type mongod directly into the command, but you will find that the service did not start, an exception was reported, and the service stopped.
  3. Create new folder: the error appears above, because we do not have the resume Mongodb required folder, generally is the root directory of the installation disk, create data/db, these two folders.
  4. Run Mongod: at this point the service can be started and the default port is 27017.

Link services:

After the server is enabled, we can use the command line to link the server. The link command is mongo. Reopen a command line tool and type the mongo command. Maybe you’ll give a few warnings when you link, but we’ll leave that alone and learn more about it later.

To check whether the database exists, run the show DBS command

Check the database version command: db.version()

If both of these commands display results correctly, our MongoDB database has been successfully installed and we can happily start learning. Want to learn friends after learning to install it by yourself, only by yourself to really learn.

Section 02: Mongo Basic command -1

In the next few sections, I will directly use Mongo command. First, I will let my partners know how to use basic commands of MongoDB. After getting used to it quickly, we will refine and upgrade these commands in future courses to form a complete MongoDB knowledge system. Friends don’t worry, let’s start learning.

mongo shell

If you have contacted the database before, you must know that each database has its own unique commands. MSSQL and MYsql use Sql commands, and the operation commands of MongoDB are the most familiar JavaScript commands in the front end. You have to be a little bit excited to see this as the front end, which is great for the front end.

Let’s start with a common assignment and output command to familiarize ourselves. To do this, you need to open the Mongo server and link to it – the mongod and Mongo commands we talked about last time. Type the following code on the command line.

var x='Hello World'
print(x)Copy the code

Note that instead of using console.log(‘ balbala ‘) for output, print(‘ balbala ‘) is used, which is slightly different.

You can also define functions:

function jspang(){
    return 'JSPang';
}Copy the code

From here, we’re using JavaScript syntax, which we can easily pick up.

MongoDB storage structure

In the past, the data structure of our relational databases was libraries at the top, tables below libraries, and data below tables. But MongoDB is different. Libraries are collections, and collections are files, as illustrated in the figure below.

In fact, a data table is a set, and a data row is a file. Of course, this is just for memorization, but there are differences in essence.

Basic Shell commands:

After understanding the storage structure, we can start to learn our basic Shell commands. Because these commands are quite basic, I will present them in the form of a list. The specific usage method can be viewed in the video.

  • If you have just installed the database, the default names will be local and admin(config). These are the default names of MongoDB databases. We will not allow these names when creating new libraries.
  • Use admin: Access data, also known as using a database. “Switched to DB admin” is displayed.
  • Show Collections: Shows collections in a database (relational types are called tables, which we’ll get used to).
  • Db: Displays the current location, which is the name of the database you are currently using. This is the most commonly used command, because you need to check your library before doing anything to avoid errors.

Conclusion: This lesson has let us enter the world of MongoDB, you will feel that it is relatively easy to use, are some basic commands, press Enter to use, but we still need to make more contact. The focus of this lesson is to change the previous idea of database storage structure and master MongoDB storage structure.

Section 03: Mongo Basic commands -2

In this lesson, we will continue to learn the basic commands of MongoDB. Last time, we learned some of the simplest view commands, such as view database, view collection, and display current location. In this class, we started to operate data and learn basic data addition, deletion, modification and check. Just watch the video and get started.

Basic commands for data operation:

  • Use db: Not only does use access a database, it also helps you create a database if the one you typed in doesn’t already exist. But it defaults to null until there is no collection.
  • Db.collection.insert (): New data set and insert file (data), when there is no collection, this time can create a new collection, and insert data into it. Demo: db. User. Insert (jspang {” name “:” “})
  • Db.collection.find (): Query all data, this command will list all data in the collection, you can see that MongoDB automatically added index values to us. Demo: db. The user. The find ()
  • Db.collection.findone (): Queries the first file data. Note that all MongoDB combination words are written in camel case.
  • Db.collection.update ({query},{modify}): Modify file data, the first is the query condition, the second is the value to be modified to. Note here that you can add additional file data items, as in the following example.
db.jspang.update({"name":"jspang"},{"name":"jspang","age":"32"})Copy the code

  • Db. Set. Remove (condition) : Delete file data, note that it should be followed by a condition. Demo: db. User. Remove (jspang {” name “:” “})
  • Db.collection.drop (): drop the entire collection.drop (): drop the entire collection.drop (): drop the entire collection.drop ().
  • Db.dropdatabase (): Drop the entire database. In the actual work, this is basically not needed, and the actual work may need to retain data and traces.

Summary: This lesson is all about data or library operations. Although these are simple, you need to use them every day, so it is recommended to practice them repeatedly to improve your memory.

Section 04: Write mongo commands in js files

Writing mongo command (shell) in the command line is really too troublesome (anyway, technology fat is unable to tolerate the Windows system of this command line), urgently need a better way to work, this lesson we learn to use JS file to write shell commands and execution. The Shell commands for writing mongo in JS are mostly the same, with only a few differences.

Write the command to JS:

Now simulate a user login log table information, write in JS. Create a gotask.js file in a new directory, such as D:/mongoShell/. The content of the document is as follows:

GoTask. Js file

var userName="jspang"; Var timeStamp= date.parse (new Date()); Var jsonDdatabase={"loginUnser":userName,"loginTime":timeStamp}; Var db = connect('log'); Db.login. insert(jsonDdatabase); Print ('[demo]log print success'); // Success is displayed with no errorsCopy the code

If the above basic code you look not so easy, then I suggest you stop learning this course first, to learn the basic knowledge of JS, only a solid foundation, learning will be fast.

Execute the JS file

Write JS file, need to execute, see if there is a problem with the file, can successfully insert data into MongoDB.

The implementation is actually quite simple, just use mongo xxx.js(XXX is the gotask.js file we wrote).

mongo goTask.jsCopy the code

Then we can see that the execution has been successful on the command line, and we can go to the terminal to view the insertion result.

Conclusion: This lesson solved the problem of writing command lines in the terminal very well. Although most shells are written in the same way as in the command line, there are some differences. I hope you can easily master this lesson.

Section 05: Correct method for batch inserts

In the first four lessons, we briefly explained how to use MongoDB to get started quickly. From the beginning of this lesson, we will explain the operations of MongoDB in detail and in depth, and the difficulty will gradually increase. You need to be reminded that if you are not familiar with the previous course, practice it first, otherwise it will be a little difficult to follow.

There are two capabilities to be aware of when operating a database:

  • The first is fast storage capacity.
  • The second is the ability to facilitate quick queries.

Batch insert:

Bulk inserts are done as arrays (3 carriage returns can be cut out if a write is wrong). We now type in the following code from the command line, and we can see that the data is inserted smoothly.

db.test.insert([
    {"_id":1},
    {"_id":2},
    {"_id":3}
])Copy the code

Older versions of MongoDB (almost all prior to 3.2) add batch words before Insert, as shown in the following code.

db.test.batchInsert([
    {"_id":1},
    {"_id":2},
    {"_id":3}
])Copy the code

Don’t insert more than 48 megabytes at a time. Try to use static storage for.zip and large images. MongoDB stores static paths as a rule.

Batch insert performance tests

Just learned batch insert, that is circular insert fast? Or batch insert faster? The general assumption is that bulk inserts are faster (there’s no doubt about that), but let’s get geeky and try writing a little Shell to verify the results.

First write a circular insert method:

var startTime = (new Date()).getTime(); Var db = connect('log'); // start loop for(let I =0; i<1000; i++){ db.test.insert({num:i}); } var runTime = (new Date()).getTime()-startTime; Print ('This run This is:'+runTime+'ms'); // Print it outCopy the code

The time of my test was 507ms. Although the speed was related to the computer performance, it was still not ideal. It took nearly half a second for 1000 pieces of data, and the team leader would be furious.

Batch insert code:

var startTime = (new Date()).getTime(); var db = connect('log'); Var tempArray = [] for(let I =0; i<1000; I ++){// loop through the array with the value temparray.push ({num: I}); } db.test.insert(tempArray) var runTime = (new Date()).getTime()-startTime; print ('This run this is:'+runTime+'ms');Copy the code

This time it took 17ms, far outperforming cyclic inserts.

Conclusion: we must take care of database performance in our work, it is also your level of cash withdrawal, a technology can be very simple, but to make a master is not so simple. After this section, remember that in your work, if you can’t decide between circular inserts and batch inserts, go for batch inserts, which will give you a better performance experience.

Section 06: Modification: Update common errors

We’ll start this lesson by going over the details of the Update. We’ll look at common errors first, and then we’ll come up with solutions when we know what the difficulties or problems are. In this lesson I will first demonstrate some incorrect Update methods and then move on to the correct ones. Hope not to mislead small partners.

Error 1: Update only modified items

If you have any experience with relational databases, it’s easy to make the mistake of changing only the one item that needs to be changed, because that’s how it’s done in relational databases. Let’s start with some data that simulates the composition of a software development team (not seriously, of course).

Var workmate1={name:'JSPang', age:33, sex:1, job:' front ', skillOne:'HTML+CSS', SkillTwo:'JavaScript', SkillThree:'PHP'}, regeditTime:new Date()} var workmate2={name:'ShengLei', age:30, sex:1, job:'JAVA backend ', skill:{ skillOne:'HTML+CSS', SkillTwo:'J2EE', SkillThree:'PPT' }, RegeditTime :new Date()} var workmate3={name:'MinJie', age:20, sex:1, job:'UI design ', Skill :{skillOne:'PhotoShop', SkillTwo:'UI', SkillThree:'Word+Excel+PPT' }, regeditTime:new Date() } var db=connect('company') var workmateArray=[workmate1,workmate2,workmate3] db.workmate.insert(workmateArray) print('[SUCCESS]: The data was inserted successfully.');Copy the code

In the above code, we inserted three pieces of data into the database as files.

At this time, I suddenly found that the gender of the UI position was wrong. Originally, she was a beautiful woman, but it was not written as male. We need to modify this data, but it is often written like this.

var db=connect('company')
db.workmate.update({name:'MinJie'},{sex:0})
 
print('[update]: The data was updated successfully');Copy the code

The problem with this is that our last entry is just sex:0, and everything else is missing, which is definitely not what we want. This is a common mistake that beginners make when performing database modifications, which is to modify only the changed data.

Correct modification method:

You can declare a variable, put all the information you want to change into the variable, and then perform the modification.

Var db=connect('company') var workmate3={name:'MinJie', age:20, sex:0, job:'UI ', skillOne:'PhotoShop', SkillTwo:'UI', SkillThree:'Word+Excel+PPT' }, regeditTime:new Date() } db.workmate.update({name:'MinJie'},workmate3) print('[update]: The data was updated successfully');Copy the code

Drop (db.workmate.drop()); drop(db.workmate.drop());

/ / execute the following command: db. Workmate. Drop () the load ('. / demo02. Js') load ('. / demo03. Js')Copy the code

Now this is the correct method, the data modification is fine, but you will find it very cumbersome to write, and very prone to errors. Next time we’ll look at the Update modifier, which solves this problem perfectly.

Section 07: Modification: Getting to know the UPDATE modifier

The changes we made last time were just not elegant enough to use and were unacceptable to a great front end, so we’re going to learn something new about the update modifier to fix this problem. Update modifiers can help us change data quickly and easily, making our operations easier and more convenient.

$set modifier

Sex = age = sex = age = sex = age = sex = age = sex = age

db.workmate.update({"name":"MinJie"},{"$set":{sex:2,age:21}})Copy the code

Once the data has been modified, we can use db.workmate.find() to check it. You can see that the data has been modified.

Modify nested content (embedded document)

For example, the skills of UI have changed. She said that she could not make PPT but word was very good and needed to be modified. At this point, you will find that the skill data is embedded. At this point, we can modify it in the form of attributes, Skill. SkillThree. Take a look at the code below.

db.workmate.update({"name":"MinJie"},{"$set":{"skill.skillThree":'word'}})Copy the code

This makes it easy to modify the embedded document.

$unset deletes the key

All it does is remove a key and a key. Generally girls do not want to see their age, so we asked to delete the age. At this point we can use the $unset form.

db.workmate.update({"name":"MinJie"},{$unset:{"age":''}})Copy the code

When you delete it and want to add it back, you can just add it using set.

$Inc calculates the numbers

It is a modification of the value, but the modification must be a number. Strings have no effect. Now we need to subtract 2 years from MiJie’s age, which can be directly operated by $inc.

db.workmate.update({"name":"MinJie"},{$inc:{"age":-2}})Copy the code

Multi options

Now the leader says, you have to add everyone’s hobbies, but if you write directly you will only add one, such as the following form.

db.workmate.update({},{$set:{interset:[]}})Copy the code

If you use db.workmate.find(), you will find that only the first data has been changed. The other two data have not been changed. The multi option is used when we want to change.

db.workmate.update({},{$set:{interset:[]}},{multi:true})Copy the code

Multi is true for all changes and false for only one (default).

Upsert options

Upsert inserts the data if no value is found. For example, we have a new colleague xiaoWang at this time. At this time, we modify his information to set age to 20 years old, but there is no such data in the collection. You can add it directly using the upsert option.

db.workmate.update({name:'xiaoWang'},{$set:{age:20}},{upsert:true})Copy the code

Upsert also has two values: true for not adding, false for not adding (the default).

Summary: This is a very informative lesson about the UPDATE modifier. Be sure to practice several times after class, or you will soon forget.

Section 08: Modify: Update array modifier

We’ve already seen some basic modifiers, but in this lesson we’ll focus on array modifiers, and of course you can modify embedded documents, that is, data in object form. Let’s study hard.

$push appends array/embedded document values

$push appends values in an array, but we often use it to manipulate embedded stable documents, namely {} objects. Let’s look at the way to append an array value, for example, we want to add an interset for Xiao Wang to draw:

db.workmate.update({name:'xiaoWang'},{$push:{interest:'draw'}})Copy the code

Of course, the $push modifier can also add value to the embedded document. For example, if we want to add a new skill called skillFour to our UI, we can do draw:

db.workmate.update({name:'MinJie'},{$push:{"skill.skillFour":'draw'}})Copy the code

The $push modifier is the most commonly used in our work, because our data typically involves arrays and embedded documents.

$ne looks for presence

And the main thing it does is it checks if a value exists, and if it doesn’t, then it does, then it doesn’t, and it’s very easy to reverse, remember I used to reverse this modifier a lot when I first learned it, and I just added a lot of holes to myself.

Example: If palyGame is not in xiaoWang’s interest, we will add Game to the hobby.

db.workmate.update({name:'xiaoWang',"interest":{$ne:'playGame'}},{$push:{interest:'Game'}})Copy the code

Summary: If there is no modification, there is no modification.

$addToSet Upgraded version of $ne

It is the upgraded version of $NE (check whether it exists, and push it if it does not exist). It is more intuitive and convenient to operate, so it is more used than $en in work.

XiaoWang’s interest is readBook. If xiaoWang’s interest is not readBook, add it to readBook.

db.workmate.update({name:"xiaoWang"},{$addToSet:{interest:"readBook"}})Copy the code

$each Specifies the value to be added in batches

It can pass in an array and add multiple values at a time, which is equivalent to batch operation. The performance is also much better than loop operation, which needs our attention. In the work, we should first combine the array and then operate in the form of batch operation.

For xiaoWang, add three hobbies at once: Sing, Dance and Code.

var newInterset=["Sing","Dance","Code"];
db.workmate.update({name:"xiaoWang"},{$addToSet:{interest:{$each:newInterset}}})Copy the code

 

$pop Deletes array values

$pop deletes only once, not all the values in the array. And it has two choices, one is 1 and minus 1.

  • 1: deletes from the end of the array
  • -1: deletes from the beginning of the array

Example: Now delete xiaoWang’s code.

db.workmate.update({name:'xiaoWang'},{$pop:{interest:1}})Copy the code

Array location modification

Sometimes we only know which digit of the array to change, but we don’t know what it is, so we can use the form interest.int.

For example, we now want to modify xiaoWang’s third interest to Code. Note that the count here starts at 0.

db.workmate.update({name:'xiaoWang'},{$set:{"interest.2":"Code"}})Copy the code

 

Summary: This lesson will focus on the update modifier for arrays and embedded documents. Of course, if you can’t remember, you should at least remember this blog address, because the technologist has sorted out the notes for you.

Section 09: Modification: State Return and Security

When operating the database, sufficient security measures should be taken to modify the data. In practice, we seldom use DB.collections. update, and we always use findAndModify to modify the data, which can return some necessary parameters and give us more control over the modification. The strengthening of control is to strengthen the ability to strengthen safety.

Reply write:

Before we dive into the code, let’s look at one concept: reply write. Print (‘ [update]:The data was updated successfully ‘);) . This is not allowed at work because we cannot withdraw the results of our modifications at all.

Reply write will give us the result (report) directly, the result will contain a lot of items, so that we can do good control and security mechanism processing. It’s kind of like the front end calling the back end interface, and whatever I do, the back end gives me some status words.

db.runCommand( ):

It is the executor for the database to run commands, and it is preferred for command execution because it provides a consistent interface between the Shell and the driver. (You can use runCommand to perform almost any operation on the database.) Now let’s try modifying the database with runCommand and see how the results differ from using db.collections.update directly.

db.workmate.update({sex:1},{$set:{money:1000}},false,true)
var resultMessage=db.runCommand({getLastError:1})
printjson(resultMessage);Copy the code

In the code above, we changed the data of all the men. We added 1000 yuan money for each man, and then executed with db.runcommand (). You can see the result returned on the console.

{
        "connectionId" : 1,
        "updatedExisting" : true,
        "n" : 2,
        "syncMillis" : 0,
        "writtenTo" : null,
        "err" : null,
        "ok" : 1
}Copy the code

  • False: The false at the end of the first sentence is short for upsert, which means that the data will not be increased without this item.
  • True: True is short for multi, which means to modify all, both of which we learned in the previous lesson.
  • GetLastError :1: indicates that a function error is returned. There are a lot of parameters here. If you are interested, please find them by yourself.
  • Printjson: output to the console as a JSON object.

Db.listcommands (): Check out all Commad commands. There are a lot of them.

For example, to check whether the connection to the database was successful, we can use the Command Command.

db.runCommand({ping:1})Copy the code

Returning OK: 1 means the link is ok.

findAndModify:

As can be seen from the name, findAndModify means findAndModify. It can be configured to return the results of modifications. Let’s start with the following code:

Var myModify={findAndModify:"workmate", query:{name:'JSPang'}, update:{$set:{age:18}}, new:true } var ResultMessage= db.runcommand (myModify); printjson(ResultMessage)Copy the code

The performance of findAndModify is not as good as using DB.collections. update directly, but it is used in practical work, after all, the security of commercial applications is still very important.

FindAndModify property value:

  • Query: The condition/document to be queried
  • Sort: sort
  • Remove: [Boolean] Specifies whether to delete the found document. Set the value to true.
  • New :[Boolean] Returns the updated document or the updated document.
  • Fields: Field to be returned
  • Upsert: Does not have this value whether to increase.

 

Conclusion: This lesson covers some safety related operations, but it is not the whole story, and we will continue to learn more as the course progresses. Try to use findAndModify to update data during work, which is safer and more intuitive, and this performance loss is worth it.

Section 10: Query: find inequality modifier

We will talk about the MongoDB search operation in several classes, because the content is relatively large, and search is the most applied operation in development, almost every module will use it, so the search part will be the most important part of this class. In this lesson we will start by looking at simple query criteria and also look at the basic use of find. If you’ve ever worked with a relational database like MySql, you’ll be familiar with things like >(greater than), <(less than), and =(equal), but non-relational databases can’t use these symbols directly, so it’s a little different.

Construction data:

We need to construct more data into the collection so that we can properly explain the query criteria, so you can copy the following code directly to add. Of course, you can add some data to the set yourself, as long as it’s convenient for us to learn.

Var workmate1={name:'JSPang', age:33, sex:1, job:' front ', skillOne:'HTML+CSS', skillTwo:'JavaScript', SkillThree :'PHP'}, regeditTime:new Date(), interest:[]} var workmate2={name:'ShengLei', age:31, sex:1, job:'JAVA backend ', skill:{ skillOne:'HTML+CSS', skillTwo:'J2EE', skillThree:'PPT' }, regeditTime:new Date(), interest:[] } var workmate3={ name:'MinJie', age:18, sex:0, job:'UI', skill:{ skillOne:'PhotoShop', skillTwo:'UI', skillThree:'PPT' }, regeditTime:new Date(), interest:[] } var workmate4={ name:'XiaoWang', age:25, sex:1, job:'UI', skill:{ skillOne:'PhotoShop', skillTwo:'UI', skillThree:'PPT' }, regeditTime:new Date(), Interest :[]} var workmate5={name:'LiangPeng', age:28, sex:1, job:' LiangPeng', skillOne:'HTML+CSS', SkillTwo :'JavaScript',}, regeditTime:new Date(), interest:[]} var workmate6={name:'HouFei', age:25, sex:0, job:' front ', skill:{ skillOne:'HTML+CSS', skillTwo:'JavaScript', }, regeditTime:new Date(), Interest :[]} var workmate7={name:'LiuYan', age:35, sex:0, skill:{skillOne:'PhotoShop', skillTwo:'CAD',}, RegeditTime :new Date(), interest:[]} var workmate8={name:'DingLu', age:20, sex:0, job:' artist ', skill:{ skillOne:'PhotoShop', skillTwo:'CAD', }, regeditTime:new Date(), interest:[] } var workmate9={ name:'JiaPeng', Age :29, sex:1, Job :' front-end ', skillOne: {skillOne:'HTML+CSS', skillTwo:'JavaScript', skillThree:'PHP'}, RegeditTime :new Date(), interest:[]} var workmate10={name:'LiJia', age:26, sex:0, job:' front ', skill:{ skillOne:'HTML+CSS', skillTwo:'JavaScript', skillThree:'PHP' }, regeditTime:new Date(), interest:[] } var db=connect('company'); var workmateArray=[workmate1,workmate2,workmate3,workmate4,workmate5,workmate6,workmate7,workmate8,workmate9,workmate10]; db.workmate.insert(workmateArray); [SUCCESS] : The data was inserted successfully');Copy the code

Simple search:

For example, we now want to find all the people in the data who are skilled in HTML+CSS. So let’s just look it up and add conditions.

db.workmate.find({"skill.skillOne":"HTML+CSS"})Copy the code

We can’t use load at this point, and I’ll show you how to do it later, but we’re going to do it the stupid way, paste and copy.

Filter field

Now there are so many data items coming back that sometimes our program doesn’t need so many options. Like we just need names and skills. At this point we need to write the second parameter, look at the following code.

db.workmate.find(
    {"skill.skillOne":"HTML+CSS"},
    {name:true,"skill.skillOne":true}
)Copy the code

You should see the following result in the terminal:

{ "_id" : ObjectId("5a611350c4e36dee6008987a"), "name" : "JSPang", "skill" : { "skillOne" : "HTML+CSS" } }
{ "_id" : ObjectId("5a611350c4e36dee6008987b"), "name" : "ShengLei", "skill" : { "skillOne" : "HTML+CSS" } }
{ "_id" : ObjectId("5a611350c4e36dee6008987e"), "name" : "LiangPeng", "skill" : { "skillOne" : "HTML+CSS" } }
{ "_id" : ObjectId("5a611350c4e36dee6008987f"), "name" : "HouFei", "skill" : { "skillOne" : "HTML+CSS" } }
{ "_id" : ObjectId("5a611350c4e36dee60089882"), "name" : "JiaPeng", "skill" : { "skillOne" : "HTML+CSS" } }
{ "_id" : ObjectId("5a611350c4e36dee60089883"), "name" : "LiJia", "skill" : { "skillOne" : "HTML+CSS" } }Copy the code

ID :false ID :false ID :false ID :false ID :false ID :false ID :false Of course, false and true here can also be represented by 0 and 1.

db.workmate.find(
    {"skill.skillOne":"HTML+CSS"},
    {name:true,"skill.skillOne":true,_id:false}
)Copy the code

When you look at the result in the terminal, it’s already what we want.

{ "name" : "JSPang", "skill" : { "skillOne" : "HTML+CSS" } }
{ "name" : "ShengLei", "skill" : { "skillOne" : "HTML+CSS" } }
{ "name" : "LiangPeng", "skill" : { "skillOne" : "HTML+CSS" } }
{ "name" : "HouFei", "skill" : { "skillOne" : "HTML+CSS" } }
{ "name" : "JiaPeng", "skill" : { "skillOne" : "HTML+CSS" } }
{ "name" : "LiJia", "skill" : { "skillOne" : "HTML+CSS" } }Copy the code

In fact, these search operations, are in the stage of doing equal, but we need more than just equal query, we need more query conditions.

Unequal modifier

  • Less than ($lt): less than
  • Less than or equal to ($LTE) : less-than-equal
  • Greater than ($gt): greater than
  • Greater than or equal to ($gte): greater-than-equal
  • Not equal to ($ne): Not equal

We’re looking for people in the company who are younger than 30 and older than 25. Look at the code below.

db.workmate.find(
    {age:{$lte:30,$gte:25}},
    {name:true,age:true,"skill.skillOne":true,_id:false}
)Copy the code

The date for

MongoDB also provides a convenient date-finding method. Now we want to find data with a registration date greater than January 10, 2018. We can write code like this.

var startDate= new Date('01/01/2018');
db.workmate.find(
    {regeditTime:{$gt:startDate}},
    {name:true,age:true,"skill.skillOne":true,_id:false}
)Copy the code

We first animate a date variable and then filter it using the greater-than character.

Summary: This lesson is not much, but if you are a DBA and use it every day in your job, this lesson is a must. If you are too lazy to do it, you may not learn the rest of the lesson.

Section 11: Queries: multi-conditional queries for find

Many times we need to query not only for a simple condition, for example, we are now looking for colleagues who are 33 and 25 years old, but also for colleagues who are over 30 and have PHP skills. MongoDB also supports this very well, so let’s take a look.

$in modifier

The IN modifier can easily handle one-key, multi-value queries. As in our example above, we now want to query for colleagues whose ages are 25 and 33.

Db. Workmate. Find ({age: {$in: [33] 25}}, {name: 1, "skill. SkillOne" : 1, age: 1, _id: 0})Copy the code

$in = $nin; $in = $nin; $in = $nin;

$or modifiers

It is used to query multiple key values, such as colleagues who are older than 30 or who can do PHP. The main difference is the two keys. The $in modifier is a Key value that needs to be memorized.

db.workmate.find({$or:[
    {age:{$gte:30}},
    {"skill.skillThree":'PHP'}
]},
    {name:1,"skill.skillThree":1,age:1,_id:0}
)Copy the code

If you are older than 30, or if you know how to do PHP. The corresponding $nor modifier is not demonstrated here, so try it out for yourself.

$and modifier

$and = $and = $and = $and = $and = $and = $and = $and Of course, it’s easier to write. Simply replace the OR in the above code with and.

db.workmate.find({$and:[
    {age:{$gte:30}},
    {"skill.skillThree":'PHP'}
]},
    {name:1,"skill.skillThree":1,age:1,_id:0}
)Copy the code

$not modifier

It is used to query for values other than conditions, for example, we are now looking for people older than 20 and younger than 30. Note that the $NOT modifier cannot be used in conditional statements and can only be used for external queries.

db.workmate.find({
    age:{
        $not:{
            $lte:30,
            $gte:20
        }
    }
},
{name:1,"skill.skillOne":1,age:1,_id:0}
)Copy the code

Conclusion: The knowledge of this lesson is relatively simple, but it is easy to confuse the memory. Fortunately, study notes have been prepared for you. Come and see when you forget.

Section 12: Query: An array query for find

This section mainly studies the query of array. In the study of update, we spent a lot of ink to talk about the operation of array. The operation of visible array is very important in MongoDB, because the data set designed by a slightly larger project is more complex, which will involve the operation of array.

To improve data

Previously, our workmate collection had very little to do with arrays, but now we add interests to the data, and add interests to each person, such as writing code, cooking, watching movies… .

Of course, you can build the data yourself, but if you don’t want to bother with your own data, you can just drop the old table and reload it.

Var workmate1={name:'JSPang', age:33, sex:1, job:' front ', skillOne:'HTML+CSS', skillTwo:'JavaScript', SkillThree :'PHP'}, regeditTime:new Date(), interest:[' watch a film ',' read a book ',' fish ',' travel ']} var workmate2={name:'ShengLei', Age :31, sex:1, Job :'JAVA backend ', Skill :{skillOne:'HTML+CSS', skillTwo:'J2EE', skillThree:'PPT'}, regeditTime:new Date(), } var workmate3={name:'MinJie', age:18, sex:0, job:'UI', skill:{skillOne:'PhotoShop', skillTwo:'UI', skillThree:'PPT' }, regeditTime:new Date(), } var workmate4={name:'XiaoWang', age:25, sex:1, job:'UI', skillOne:'PhotoShop', skillTwo:'UI', skillThree:'PPT' }, regeditTime:new Date(), @liangpeng = @liangpeng = @liangpeng = @liangpeng = @liangpeng = @liangpeng = @liangpeng = @liangpeng = @liangpeng = @liangpeng = @liangpeng SkillTwo :'JavaScript',}, regeditTime:new Date(), interest:[' play game ',' write code ',' cook ']} var workmate6={name:'HouFei', age:25, Sex :0, job:' front-end ', Skill :{skillOne:'HTML+CSS', skillTwo:'JavaScript',}, regeditTime:new Date(), } var workmate7={name:'LiuYan', age:35, sex:0, job: {skillOne:'PhotoShop', SkillTwo :'CAD',}, regeditTime:new Date(), interest:[' paint ',' party ',' watch ']} var workmate8={name:'DingLu', age:20, sex:0, Job :' art ', Skill :{skillOne:'PhotoShop', skillTwo:'CAD',}, regeditTime:new Date(), } var workmate9={name:'JiaPeng', age:29, sex:1, job:' front ', skill:{skillOne:'HTML+CSS', skillTwo:'JavaScript', skillThree:'PHP' }, regeditTime:new Date(), Var workmate10={name:'LiJia', age:26, sex:0, skill:{skillOne:'HTML+CSS', skillTwo:'JavaScript', skillThree:'PHP' }, regeditTime:new Date(), Interest: [' game ', 'food', 'basketball']} var db = connect (" company "); var workmateArray=[workmate1,workmate2,workmate3,workmate4,workmate5,workmate6,workmate7,workmate8,workmate9,workmate10]; db.workmate.insert(workmateArray); [SUCCESS] : The data was inserted successfully');Copy the code

Basic array query

For example, now that we know a person’s hobbies are ‘painting’, ‘partying’, ‘going to the movies’, but we don’t know who it is, we can use the simplest array query (in practice, this kind of situation is rarely used, so this query is just a store of knowledge).

Db. Workmate. Find ({interest: [' drawing ', 'party', 'watching movies']}, {name: 1, interest: 1, age: 1, _id: 0})Copy the code

After running it in the terminal, we get the data. At this point, we said, we want to find out the information of employees who watch movies as a hobby. Logical, the following code would be used.

Db. Workmate. Find ({interest: [' watching movies']}, {name: 1, interest: 1, age: 1, _id: 0})Copy the code

After running, we did not get the corresponding personnel data as we expected, the data is empty. So what’s the problem? The problem is that we write a parenthesis ([]), because the parenthesis is equivalent to a perfect match, so we do not get a single data that meets the query conditions. Let’s get rid of the brackets and see what happens.

Db.workmate. find({interest: 1,interest:1,age:1,_id:0}) db.workmate.find({interest: 1,interest:1,age:1,_id:0})Copy the code

That’s how we query an item in an array, and that’s the simplest way to use an array query.

$all- Array multiple query

$all = $all = $all = $all = $all = $all Look at the following example:

Db. Workmate. Find ({interest: {$all: [" the movies ", "reading"]}}, {name: 1, interest: 1, age: 1, _id: 0})Copy the code

At this time I found people who were interested in both watching movies and reading books.

$in- Array or query

With the $all modifier, all conditions need to be met. If $in mainly satisfies one of the items in the array, it can be detected (sometimes confused with $or). For example, we now need to query the information of employees whose hobbies include watching movies or reading books.

Db. Workmate. Find ({interest: {$in: [" the movies ", "reading"]}}, {name: 1, interest: 1, age: 1, _id: 0})Copy the code

$size- Query the number of arrays

The $size modifier queries the result based on the number of arrays. For example, if the number of people we are looking for is 5, we can use $size.

db.workmate.find(
    {interest:{$size:5}},
    {name:1,interest:1,age:1,_id:0} 
)Copy the code

At this point, the personnel with 5 hobbies will be displayed.

$slice- Display option

Sometimes I don’t want to display all the values in the array, but just the first two items, for example we now want to display the first two items of everyone’s interest, instead of showing everyone’s interest.

db.workmate.find(
    {},
    {name:1,interest:{$slice:2},age:1,_id:0} 
)Copy the code

The first two items of each person’s interest are now displayed. If we wanted to show the last item of interest, we could simply use slice:-1 to query.

db.workmate.find(
    {},
    {name:1,interest:{$slice:-1},age:1,_id:0} 
)Copy the code

Conclusion: If you just watch videos, you can’t learn it, you have to practice it, and I emphasize that over and over again in all the videos, the goal is to get you to actually learn it and apply it to your work.

 

Section 13: Query: use of find parameters

In the previous three sections, we’ve looked at queries that operate on the first (query) and second (fields) arguments to the find method. Find also has several common parameters that are used for paging and sorting. In this section we’ll take a look at some of these common options and demonstrate the effect of a pagination.

The find parameters:

  • Query: This is the query criterion, the default first parameter of MongoDB.
  • Fields :(return content) the style of the results that will be displayed after the query. You can use true or false to control whether the query will be displayed.
  • Limit: The number returned, followed by a number, to control the number of results returned per query.
  • Skip: How many displays can be skipped.
  • Sort: sort by 1 from smallest to largest and -1 from largest to smallest.

Paging Demo:

With these options out of the way, we can now do the simplest pagination. We’ll page colleague collections, showing two on each page, in ascending order of age.

db.workmate.find({},{name:true,age:true,_id:false}).limit(0).skip(2).sort({age:1});Copy the code

$where modifier

It’s a very powerful modifier, but behind that power comes risk. It allows us to use javascript methods in conditions to perform complex queries. Let’s start with the simplest example, where we want to query for people older than 30.

db.workmate.find(
    {$where:"this.age>30"},
    {name:true,age:true,_id:false}
)Copy the code

Here this refers to the workmate (query collection) itself. So we can call it anywhere we want in our program. While powerful and flexible, such queries can be stressful and securitizing to the database, so minimize the use of the $WHERE modifier in your work.

Section 14: Query: How to use find in JS text (end)

The previous use of find is JS written in text, and then copied to the terminal to execute, which is very troublesome. I’ve had a lot of people ask me how to run it directly from text, just like writing an UPDATE statement. In this lesson we are going to learn how to execute directly in text.

HasNext loop result

To execute our find statement in text using cursor and loop operations, take a look at the code, where I’ve commented out each sentence.

Collection var result = db.workmate.find() var result = db.workmate.find() var result = db.workmate.find() Assign the query result to result // loop the result using the cursor's hasNext(). While (result.hasnext ()){printjson(result.next())}Copy the code

Once done, you can now load() from the terminal without having to copy and paste.

The forEach loop

To use the hasNext loop, we need the help of while. MongoDB also provides a forEach loop. Now modify the above code and use the forEach loop to output the result.

Collection var result = db.workmate.find() var result = db.workmate.find() var result = db.workmate.find() Assign the query result to result // loop the result using the cursor's hasNext(). result.forEach(function(result){ printjson(result) })Copy the code

Personally, the forEach loop is more elegant. Both of these methods are very good, with their own hobbies to choose.

Summary: that we MongoDB of the basic part of all finished, we learned its add, delete, change, search, you can also use MongoDB for some operations. Note that this is just the end of this article. In the next article we will cover MongoDB and start with MongoDB indexes.

Section 15: Indexing: Constructing mega data

Index performance must have a large number of data to see, you said that you have 10 20 data, it is impossible to see the effect, this class through random number method, to create a database of millions of data. (Watch the video to learn).

Install the Node

For the sake of course debugging code, we will install Node to execute JS on the terminal and see the result.

Node download address: https://nodejs.org/en/ (download the LTS version directly)

Installation is very simple, as long as you can install QQ, you should be able to install, has been the next step is no problem. Once installed, there is no need to configure our environment variables.

You can enter node -v in the terminal to check whether the installation is successful. If the version number is displayed, the installation is successful.

Method of making random number:

If we want to generate a data set of millions, we must have the participation of random numbers, we need to write a method of random numbers. The following code creates a random number method.

Function GetRandomNum(min, Max){let range = max-min; Let rand = math.random (); Return (min + math.round (rand *range)); } console.log(GetRandomNum(10000,99999));Copy the code

Create a random username:

With the random number method, we can make a randomly generated username. The purpose is to have different user names so that we can test the query speed.

Function GetRandomNum(min, Max){let range = max-min; Let rand = math.random (); Return (min + math.round (rand *range)); //console.log(GetRandomNum(10000,99999)); / / to generate random username function GetRadomUserName (min and Max) {let tempStringArray = "123456789 qwertyuiopasdfghjklzxcvbnm". The split (" "); Let outPuttext = ""; For (let I =1; for(let I =1; i<GetRandomNum(min,max); I++){// randomly select letters, OutPuttext =outPuttext+tempStringArray[GetRandomNum(0,tempStringArray.length)]} return outPuttext; } the console. The log (GetRadomUserName 16th (7))Copy the code

Insert 2 million data

With a way to generate random numbers and random usernames, you can produce millions of data. This code is explained in detail in the video. The code is as follows:

var db = connect('company'); db.randomInfo.drop(); var tempInfo = []; for (let i=0; i<2000000; I++) {tempInfo. Push ({username: GetRadomUserName 16th (7), regeditTime: new Date (), randNum0: GetRandomNum (100000999 999), RandNum1: GetRandomNum (100000999 999), randNum2: GetRandomNum (100000999 999), randNum3: GetRandomNum (100000999 999), RandNum4: GetRandomNum (100000999 999), randNum5: GetRandomNum (100000999 999), randNum6: GetRandomNum (100000999 999), RandNum7: GetRandomNum (100000999 999), randNum8: GetRandomNum (100000999 999), randNum8: GetRandomNum (100000999 999), }) } db.randomInfo.insert(tempInfo);Copy the code

This process may take 2-3 minutes, depending on your computer configuration, will vary.

Once the insertion is complete, we can use the command db.randominfo.stats () to see the number of entries in the data.

Full code:

Function GetRandomNum(min, Max){let range = max-min; Let rand = math.random (); Return (min + math.round (rand *range)); //console.log(GetRandomNum(10000,99999)); / / to generate random username function GetRadomUserName (min and Max) {let tempStringArray = "123456789 qwertyuiopasdfghjklzxcvbnm". The split (" "); Let outPuttext = ""; For (let I =1; for(let I =1; i<GetRandomNum(min,max); I++){// randomly select letters, OutPuttext =outPuttext+tempStringArray[GetRandomNum(0,tempStringArray.length)]} return outPuttext; } // console.log(GetRadomUserName(7,16)) // var startTime=(new Date()).gettime (); var db = connect('company'); db.randomInfo.drop(); var tempInfo = []; for (let i=0; i<2000000; I++) {tempInfo. Push ({username: GetRadomUserName 16th (7), regeditTime: new Date (), randNum0: GetRandomNum (100000999 999), RandNum1: GetRandomNum (100000999 999), randNum2: GetRandomNum (100000999 999), randNum3: GetRandomNum (100000999 999), RandNum4: GetRandomNum (100000999 999), randNum5: GetRandomNum (100000999 999), randNum6: GetRandomNum (100000999 999), RandNum7: GetRandomNum (100000999 999), randNum8: GetRandomNum (100000999 999), randNum8: GetRandomNum (100000999 999), }) } db.randomInfo.insert(tempInfo);Copy the code

 

Conclusion: This lesson is mainly to explain the MongoDB index preparation, we use random number method to build a million level of data table, if you are interested in continuing to learn connections, this lesson must do. The rest of this article will be based on this code.

Section 16: Indexing: An introduction to indexing

There are now 2 million pieces of data in the collection, ready for indexing. Let’s start by building an index and see how many times its query performance improves. The content of this lesson will not be difficult, mainly to master the establishment of index method.

Common Query performance

Let’s make a normal query, find a random user name, and calculate the query and print time, because there are 2 million data, so the performance is not very high.

Var startTime = new Date().getTime() var db = connect('company' ForEach (rs=>{printjson(rs)}) var runTime = new Date().getTime()-startTime; Print ('[SUCCESS]This run time is:'+runTime+'ms'Copy the code

The above code is just a normal query, but it records the time. After the terminal runs, it can be estimated that the running time is about 0.8 seconds (computer performance varies), the first no cache running time is about 3.5 seconds. That’s not enough time for our daily inquiries.

indexing

Try to index the username. It only takes one sentence to create an index.

db.randomInfo.ensureIndex({username:1})Copy the code

View existing indexes

db.randomInfo.getIndexes()Copy the code

The result of the terminal now has only one index value:

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "company.randomInfo"
        }
]Copy the code

Now use the command to establish the index db. RandomInfo. EnsureIndex ({1} uername:), my computer to about 50 seconds, establishing good after us to use the randomInfo. GetIndexes (), check the results.

The result is this: it has become two indexes.

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "company.randomInfo"
        },
        {
                "v" : 2,
                "key" : {
                        "username" : 1
                },
                "name" : "uername_1",
                "ns" : "company.randomInfo"
        }
]Copy the code

Then let’s load the demo07.js file (load(‘./demo07.js’)) and see how many seconds it takes to query it. At this time, the query time is shortened to about 4ms, and the query performance is improved about 200 times.

Conclusion: Indexing is very important in both relational and document databases. As mentioned above, indexing is a thing that consumes disk and memory resources, so it has to be built according to the needs of the program. MongoDB also limited us to 64 index values.

Section 17: Index: composite index

In this lesson, we will take a look at what kind of data you can slow down using indexes, and then learn the syntax and use of compound indexes. Through this lesson, we need to understand all the use of the timing, to avoid unnecessary trouble.

A pit in the index

I remember that when I first learned MongoDB and learned index, I wanted to use it everywhere, even for collections of hundreds of data. I also used it wisely, but the result was often gilding the lily and making many detdettions. Based on actual development and performance comparisons, I’ve come up with a few (not necessarily true, but based on my own experience) situations where indexes are not used.

  • If the data number does not exceed 10,000, you do not need to use an index. The performance improvement is not obvious, but the consumption of memory and hard disk is greatly increased.
  • Do not use index field queries when the query data exceeds 30% of the table data volume. It turns out to be slower than not using the index because it retrieves a lot of the index table and our original table.
  • Numeric indexing, which is much faster than string indexing, is a clear choice in the face of millions or even tens of millions of data volumes.
  • Make the data you frequently query into an embedded data (object type data) and index it collectively.

The composite index

Okay, so we’ve talked a lot about this theory, but now we look at composite indexes. A composite index is one that has more than two indexes. Last time we indexed the username field. Now we index randNum0 as well.

db.randomInfo.ensureIndex({randNum0:1})Copy the code

After the establishment, we use the query index status command to query.

db.randomInfo.getIndexes()Copy the code

At this point, there are two custom indexes, and there are three indexes.

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "company.randomInfo"
        },
        {
                "v" : 2,
                "key" : {
                        "username" : 1
                },
                "name" : "username_1",
                "ns" : "company.randomInfo"
        },
        {
                "v" : 2,
                "key" : {
                        "randNum0" : 1
                },
                "name" : "randNum0_1",
                "ns" : "company.randomInfo"
        }
]Copy the code

Both indexes are queried simultaneously

Let’s query the values of both indexes at the same time to see what happens.

var startTime=new Date().getTime();
var db = connect('company');
 
var  rs= db.randomInfo.find({username:'7xwb8y3',randNum0:565509});
 
rs.forEach(rs=>{printjson(rs)});
 
 
var runTime = new Date().getTime()-startTime;
print('[Demo]this run time is '+runTime+'ms');Copy the code

In terms of performance, there is no special change, and the query time is still around 4ms. MongoDB’s composite queries are queried in our index order. This is the array we queried with db.randominfo.getIndexes ().

Specify index query (hint)

At the beginning of the course, I said that numeric indexes are faster than string indexes, and that this requires a way to break the query order of the index table and use our own index preference, which is hint().

var  rs= db.randomInfo.find({username:'7xwb8y3',randNum0:565509}).hint({randNum0:1});Copy the code

Due to the amount of data and complexity of chengdu is still not large, so you can not see the obvious performance improvement, but to believe that technology fat, such as big data in the work, will be very good results.

Remove the index

When an index isn’t performing well or doesn’t work, we need to drop it, using dropIndex().

db.randomInfo.dropIndex('randNum0_1'); // The unique ID of the indexCopy the code

Note here that the value entered when deleting is not our field name (key), but the value of name in our index query table. This is a small pit, I hope friends do not step in.

Summary: This section is still the main content of the operation index, including the creation of composite index, delete. And some tips on using indexes.

Section 18: Index: Full-text index

Sometimes you need to search for keywords in large articles, for example, each article I write is more than 10,000 words, at this time you want to search keywords is very difficult, MongoDB provides full-text index for us.

Preparations:

In this section, we’ll set up a collections-info and insert a little article that will provide the data for the full-text index. We’re not going to set up millions, we’re just going to look at the effect.

db.info.insert({contextInfo:"I am a programmer, I love life, love family. Every day after work, I write a diary."})
db.info.insert({contextInfo:"I am a programmer, I love PlayGame, love drink. Every day after work, I playGame and drink."})Copy the code

Of course this is very simple, but again this is only for the article, in practice there is no need to build a full-text index for such simple data.

Setting up full-text indexes

db.info.ensureIndex({contextInfo:'text'})Copy the code

It is important to note that the text keyword is used to represent the full-text index, so we will not build the data model here.

Full-text index search

Set up the full text index can be searched, the search needs two key modifiers:

  • $text: indicates to look something up in the full-text index.
  • $search: What is followed by the search.
db.info.find({$text:{$search:"programmer"}})Copy the code

Find more than one word

Full text index supports multiple lookups. For example, we want to find data with programmer, family, diary, and drink (this is the relationship of or), so both data will appear.

db.info.find({$text:{$search:"programmer family diary drink"}})Copy the code

If we want to find no record of the word drink at this point, we can use the “-” minus sign to cancel.

db.info.find({$text:{$search:"programmer family diary -drink"}})Copy the code

Escape character:

Full text search supports escape characters. For example, if we want to search for two words (love PlayGame and drink), we need to use \ slashes to change meaning.

db.info.find({$text:{$search:"\"love PlayGame\" drink"}})Copy the code

Summary: Full-text index is often used in the work, such as the search of blog articles, keyword search of long files, these need to use full-text index to carry out. The knowledge of this class is not difficult, or that sentence, you see is impossible to learn, must practice. Index, of course, there are a lot of knowledge, here we only talk about the most commonly used knowledge, the small partner into the door is good, that is to say, with 20% of the energy, learn 80% of the knowledge, and then in the work of iteration hone. While the MongoDB index article is over, the MongoDB article is not, and the next article will start learning how to manage MongoDB.

Section 19: Administration: User creation, deletion, and modification

When you install MongoDB, it gives you a default admin privilege for managing your database. You can use Mongo to connect to your database. That’s how it works. However, this user is not generally used in actual development, because security and reliability are not suitable for all known and highest permission reasons, so it is necessary to manage MongoDB users. In this lesson, we will take a look at MongoDB user management.

Create a user:

The first step is to enter our admin library by using use admin. Once inside, you can use Show Collections to view collections in the database. The default is only one collection (system.version).

The db.createUser method is used to create a user. There are a lot of parameters in the db.createUser method. I write the code below and explain each one.

Db.createuser ({user:"jspang", PWD :"123456", customData:{name:' technical fat ', email:'[email protected]', age:18,}, roles:['read'] })Copy the code

We can also configure the privileges of a separate database. For example, we want to configure the privileges of the Compay database to read and write:

Db.createuser ({user:"jspang", PWD :"123456", customData:{name:' technical fat ', email:'[email protected]', age:18,}, roles:[ { role:"readWrite", db:"company" }, 'read' ] })Copy the code

 

Built-in roles:

  1. Database user roles: read and readWrite.
  2. Database management roles: dbAdmin, dbOwner, and userAdmin.
  3. Cluster management roles: clusterAdmin, clusterManager, clusterMonitor, and hostManage.
  4. Backup and restoration roles: Backup and restore.
  5. All database roles: readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, and dbAdminAnyDatabase
  6. Super user role: root
  7. Internal roles: __system

Finding User Information

We can directly use the search method, search for user information. The command is simple:

db.system.users.find()Copy the code

Delete a user:

Delete fame and wealth is also very simple, directly with remove can delete the user’s information and permission.

db.system.users.remove({user:"jspang"})Copy the code

Built right:

Sometimes we need to verify that a user’s username and password are correct, using the robust operations MongoDB provides. It’s also a login operation, but MongoDB calls it a build right.

db.auth("jspang","123456")Copy the code

Returns 1 if it is correct and 0 if it is wrong. (Error: Authentication failed.)

Start building the right

Restart the MongoDB server, and then set that you must log in using permissions.

mongod --authCopy the code

After startup, user login can only use username and password to log in, the original mongo-style link no longer works. The corresponding user permissions are also appropriate. In a real project we have to start the server using the build form.

The login

If the user wants to log in after configuring the user, the user can use the form of Mongo, but the user name and password need to be configured:

Mongo -u jspang -p 123456 127.0.0.1:27017/adminCopy the code

At this point we can use the permissions given to us to operate on the database.

Section 20: Management: Backup and restore

As a database administrator, database backup and restore is compared to two tasks. In fact, it is quite simple to use, mongodump and mongorestore two commands.

The data backup

Take a look at the basic format of a Mongodump backup, which is essentially a command executed on a terminal.

Mongodump --host 127.0.0.1 --port 27017 --out D:/databack/backup -- Collection myCollections --db test --username username --password passwordCopy the code

For example, if we backed up all MongoDB libraries to the databack folder on drive D, we could write the command like this

Mongodump --host 127.0.0.1 --port 27017 --out D:/databack/Copy the code

Data recovery

Once backed up, we need to restore the database if there is an accident or an attack, using the mongorestore command.

Let’s take a look at the basic format

Mongorestore --host 127.0.0.1 --port 27017 --username username --password password <path to the backup>Copy the code

Let’s say we accidentally deleted a Collections data and want to restore it. Now delete the randomInfo collection.

db.randomInfo.drop()Copy the code

Use commands to restore data

Mongorestore --host 127.0.0.1 --port 27017 D:/databack/Copy the code

Summary: The two commands are so simple that you can even write a script and a timed task and let him perform it himself every day. However, if you do use MongoDB, this is a very basic operation and should be used.

 

Section 21: Management: Graphical Interface Management (Finished)

In this lesson, we are going to focus on the graphical interface. Graphical interface is relatively simple, especially since we already know a lot of terminal operation methods, so I will not write the article, you can directly watch the video.