MongoDB database
1.1 Introduction to NoSQL
With the rise of Internet web2.0 website, traditional SQL database (relational database) has been unable to cope with web2.0 website, especially the super-large-scale and highly concurrent SNS (social network system, Renren) type web2.0 pure dynamic website, which has exposed many problems that are difficult to overcome, while the non-relational database has been very strong because of its own characteristics. Rapid development. NoSQL database is created to solve the challenges brought by multiple data types in large-scale data aggregation, especially the big data application problems.
Traditional databases MySQL, SQL Server, Oracle and Access are all SQL structured databases.
The characteristic of these structured databases is that "table" has a clear concept of "field (column)", and the field is fixed. If you want to add fields, all existing entries need to be changed.
The advantage of SQL is that the query can be very complex, such as searching all "girls whose Chinese scores are higher than math scores and whose English scores are in the top three of the class".
But now, you will find that many times retrieval can be very simple, not so complicated. For example, the telephone fee is detailed and there is no need to retrieve: the call lasts more than 5 minutes and is actively dialed at night.
Disadvantage of structured databases: If fields need to be added in the future, all previous entries should be added together. For example, you have 20,000 entries. If you suddenly need to add a Chinese score field, then 20,000 existing entries need to change the field, which is particularly time-consuming. That is to say, flexibility is not enough!
The advantages of structured database: fast search, the concept of primary key, slave key, master-slave search, mapping and other advanced database concepts.
In this age of SQL, the advantages have been reduced and the disadvantages have been magnified.
NoSQL database is very suitable if you only need to save and do not need to search precisely.
China Unicom's online records, everyone will have a pile of data, this data is: as long as you save, basically do not need to find. And often the structure changes.
So MySQL and other structured data, their advantages (fast search, master-slave search advanced functions) we are more and more unused, shortcomings (the structure is difficult to change) we need more and more. So people began to reflect on the SQL database.
So it's called NoSQL, a non-relational database. Data does not have the concept of rows and columns. It uses k-v to store children or JSON. Advantages and disadvantages happen to be reversed by SQL type, which is suitable for structural changes and not suitable for precise search. Just adapted to the era of "as long as storage, not search".
NoSQL has a nickname called Not Only SQL, not just database. Actually, it's a joke. It's much weaker than SQL.
This paper introduces two most commonly used databases in work: MongoDB (Document Database) and Redis(K-V Pair Database). They are NoSQL.
Document-based databases (such as MongoDB) have the advantages of less stringent data structure, variable table structure, and no need to pre-define table structure like relational databases.
Non-relational databases are now widely used: social platforms, APP communication records, bank pipelining, telecommunications call details and so on. Any usage scenario that only needs to be saved but does not need to be finded accurately can be used with a non-relational database.
NoSQL is a non-relational database, and the fields of each entry are not fixed. Take MongoDB as an example:
{"name":"Xiao Ming","age":12,"sex":"male"} {"name":"Xiaohong","age":13,"sex":"female"} {"name":"Xiaogang","age":14,"sex":"male", "chengji":99} {"name":"Small black","age":14,"sex":"male", "gongzi":5000}
1.2 MongoDB database installation
In order to simulate a project and, more importantly, let you understand the interaction mode between the front end and the back end, we must learn the database and have the whole stack thinking.
MongoDB is a NoSQL (No Only SQL, non-relational database) database.
MongoDB is not software, but a bunch of CLI s.
MongoDB is green, which means that decompression is available without installation.
Official website: https://www.mongodb.com/
Download address: https://www.mongodb.com/download-center
Unzip to your computer disc character (do not appear in Chinese): C: Program Files
After decompression, the painting style is as follows:
The exe files provided in the bin folder, instead of double-clicking, should be run in cmd. They are CLI programs:
Setting this bin folder as an environment variable of the system ensures that CMD can run them under any disk symbol.
|
Right-click Properties on Computer |
|
Change environment variables as shown |
|
Copy in the path of the bin folder. |
|
Open CMD and enter it under any disk symbol mongo -version You can view the version. |
|
If the environment variable is not set correctly, an error will be reported. |
The use of the database requires you to install a windows patch: KB2731284.
If the patch is not installed, check the method:
https://jingyan.baidu.com/article/fd8044fa3c47e15031137acd.html
1.3 Start-up of Database
Create a folder called database on the c disk and open the cmd input:
mongod --dbpath c:\database
The mongod Express startup command opens the data library, --dbpath indicates the location of a database to be selected.
Do not close this CMD, the database will be closed when it is closed. At this time, open a new CMD window to do other operations:
mongo
Enter the REPL environment of MongoDB
1.4 Use of database
Start up first, then build a new CMD warehouse, use the mongo command to manage the data, and enter the mongo return in cmd.
Let's try to see that in mongo's REPL environment is > rather than C: Users admin > C MD environment:
Create (switch) databases:
use student
Insert data:
db.banji0902.insert({"name":"Xiao Ming", "age":12})
Query all:
db.banji0902.find()
Accurate query:
db.banji0902.find({"name":"Xiao Ming"})
1.5 MongoDB hierarchy
From big to small in MongoDB: Database > collections > Documents > records
Come from: https://docs.mongodb.com/manual/introduction/
3.5.1 records entry and documents document
record (entry)
Recording in MongoDB is a file, which is a data structure consisting of field and value pairs. MongoDB documents are similar to JSON objects. Field values can include other documents, arrays, and document arrays.
A document in documents is also called a record entry. The entry is similar to JSON structure and is a k-v pair. The value can be other objects, arrays, and arrays of objects.
1.5.2 collections set (table)
MongoDB uses collections collections to store documents, which are equivalent to "tables" in SQL. But unlike tables, collections do not require documents to have the same schema.
Below is a collection of four documents with three entries (name, age, sex)
{"name":"Xiao Ming","age":12,"sex":"male"} {"name":"Xiaohong","age":14,"sex":"female"} {"name":"Small black","age":14,"sex":"male"} {"name":"Small basket","age":13,"sex":"male"}
Documents are stored in collections (tables), and collections are stored in databases.
1.5.3 database
There can be many collections (tables) in the database.
1.6 Common CMD commands
The control of mongodb generally uses CMD commands, but there are also visual database software.
There are two kinds of orders:
CMD command
REPL command (you can enter this environment with mongo and enter it at the small pointer ">" prompt)
First learn what commands can be run in CMD?
mongod means boot, mongo means REPL environment entering database, mongo import import import data and mongo export export export data.
Start up first, and all future operations must start up first:
mongod --dbpath c:\database
First of all, to prepare external data and write several documents, it must be a. txt file, not a. json file.
Import data, create a new CMD window, enter:
Mongoimport-d student-c banji0902. / simulated data. txt
Delete old data and import new data
Mongoimport-d student-c banji0902. / analog data. txt--drop
Export data in specified databases and collections (tables):
mongoexport -d student -c banji0902 -o c:\haha.txt
- d represents the specified database - c denotes the specified table name - o denotes the export path -- drop represents data before emptying
1.7 Common REPL commands
After booting, another CMD window, input mongo and press Enter to the REPL environment of the database, and then operate the database.
Switch (create) a database:
use student
Query which databases are currently available:
show dbs
See which collections (tables) are in the current database
show collections
Delete the database:
db.dropDatabase()
Insert data into the table:
db.banji0902.insert({"name":"Xiao Ming", "age":12})
All data in the query table:
db.banji0902.find()
Accurate query:
db.banji0902.find({"name":"Xiao Ming"})
And look up: look up age is 18, and male
db.banji0902.find({"sex":"male", "age":18})
Or ($or) Search: Search for an 18-year-old or "male"
db.banji0902.find({$or:[{"sex":"male"}, {"age":38}]})
Greater than ($gt):
db.banji0902.find({"age":{$gt:18}})
Greater than or equal to ($gte), less than ($lt), less than or equal to ($lte)
Look for boys, aged between 18 and 25:
db.banji0902.find({"sex":"male", "age":{$gte:18, $lte:25}})
Regular expressions can be used in queries:
db.banji0902.find({"name":/Small/g})
Query people who like to fight against landlords:
db.banji0902.find({"hobby":"Fight against landlords"})
Modify ($set):
db.banji0902.update({"name":"Small 1"}, {$set:{"sex":"Manly woman"}})
Delete a data:
db.banji0902.remove({"name":"Small 1"})
1.8 MongoDB and Nodejs Connections
Official API: http://mongodb.github.io/node-mongodb-native/2.2/
Add, delete and change check (CRUD) operation: http://mongodb.github.io/node-mongodb-native/2.2/tutorials/crud/
Install the dependencies of mongodb, and install the specified version number. Do not install the latest version:
npm install mongodb@2.2.28 --save
Note: The API of the mongodb version is different, so it depends on the official documents:
http://mongodb.github.io/node-mongodb-native/3.0/
var MongoClient = require("mongodb").MongoClient; //Leading bag //Database Address var dbUrl = 'mongodb://127.0.0.1:27017/student'; //Connect to the database MongoClient.connect(dbUrl, function(err,db){ if(err){ console.log("Failure of database connection"); return; } console.log("Successful database connection!"); db.close(); })
Query data:
var MongoClient = require("mongodb").MongoClient; //Leading bag //Database Address var dbUrl = 'mongodb://127.0.0.1:27017/student'; //Connect to the database MongoClient.connect(dbUrl, function(err,db){ if(err){ console.log("Failure of database connection"); return; } console.log("Successful database connection!"); //Query the current database banji0902 Table data db.collection("banji0902").find({"age":{$gt:18}}).toArray(function(err,data){ console.log(data); db.close(); }) })
Traditional connection restrictions are generally not used because:
l. The callback function is ugly.
l. Inconvenient MVC programming
l. Complexity of native API s
Mongoose database
2.1 Additional data
Official website: https://mongoosejs.com/
node.js'elegant mongodb object modeling.
Installation Dependency:
npm install --save mongoose@4
Write a Hello World. Routine: Introducing packages, creating schema s, creating models, instantiating models, calling save() methods.
var mongoose = require("mongoose"); //Leading bag //Connect to the database. The database is called iqd,If the database does not exist, it will be created automatically mongoose.connect("mongodb://127.0.0.1:27017/iqd", {useMongoClient:true}); //Create a database structure( Schema) var studentSchema = { name:String, age:Number, sex:String } //Create the model (returns a class),student Is the name of the table (collection) //Attention: in nodejs The surface created in the“ student",But it will be automatically added to the database. s,Become " students" var Student = mongoose.model('student', studentSchema); //new An example var xiaoming = new Student({"name":"Xiao Ming","age":12,"sex":"male"}); //Save data xiaoming.save();
Run node app.js
iqd data is automatically created and a table called student is created (the database automatically adds s s), so it becomes student s
Start-up, REPL and console each have a CMD.
mongoose is such a philosophy that developers can not feel that they are manipulating data. They can manage databases only by using new save and other classes and instances. Besides new and svae(), they can create data, and they can also create databases by Student.insert({}).
2.2 search
lookup//Method of querying database 1: Student.find({"age":{$gt:18}}, function(err,data){ console.log(data) }) //Method of querying database 2: Student.find({"age":{$gt:18}}).exec(function(err,data){ console.log(data) })