Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
A: hi! ~ Hello, everyone, I am YK bacteria 🐷, a front-end microsystem ✨, like to share their small knowledge 🏹, welcome to follow me 😘 ~ [wechat account: YK2012YK2012, wechat official account: ykyk2012]
1. Introduction
What is a database?
- A database is a warehouse that organizes, stores, and manages data according to data structures
- Our programs are run in memory, and once the program is finished or the computer is powered down, the data in the program is lost
- Therefore, we need to persist the data of some programs to the hard disk to ensure the security of data. Databases are the best choice for data persistence
- To sum up, a database is a warehouse for storing data
Classification of databases
- Relational database (RDBMS)
- MySQL, Oracle, DB2, SQL Server…
- A relational database is full of tables
- Non-relational database (No SQL)
- Mongo, Redis…
- Key-value database
- Document database MongoDB
NoSQL refers to a non-relational database. NoSQL is sometimes called Not Only SQL abbreviation, is different from the traditional relational database database management system.
NoSQL is used to store very large scale data. (Google or Facebook, for example, collect trillions of bits of data for their users every day). These types of data stores do not require fixed schemas and can scale horizontally without unnecessary operations.
MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications.
MongoDB is a product between relational database and non-relational database. Among non-relational databases, it has the most rich functions and is the most like relational database.
RDBMS vs NoSQL
RDBMS
- Highly organized structured data
- Structured Query Language (SQL)
- Data and relationships are stored in separate tables.
- Data manipulation language, data definition language
- Strict consistency
- Based on the transaction
NoSQL
- Stands for more than just SQL
- There is no declarative query language
- There are no predefined patterns
– Key-value pair storage, column storage, document storage, graphic database
- Final consistency, not ACID properties
- Unstructured and unpredictable data
- The CAP theorem
- High performance, high availability and scalability
Some differences in terminology
SQL terms/concepts | MongoDB terminology/concepts | Explanation/explanation |
---|---|---|
database | database | The database |
table | collection | Database tables/collections |
row | document | Data record line/document |
cloumn | field | Data fields/fields |
index | index | The index |
table joins | / | Table joins, MongoDB does not support |
/ | The embedded document | MongoDB replaces multi-table joins by embedding documents |
primary key | primary key | Primary key. MongoDB automatically sets the _ID field as the primary key |
Advantages/disadvantages of NoSQL
Advantages:
- High scalability
- Distributed computing
- Low cost
- Architectural flexibility for semi-structured data
- No complicated relationship
Disadvantages:
-
No standardization
-
Limited query functionality (so far)
-
The final consensus is an unintuitive program
-
MongoDB is a database system designed for rapid development of Internet Web applications
-
MongoDB was designed to be minimal, flexible, and part of the Web application stack
-
The data model of MongoDB is document-oriented. The so-called document is a structure similar to JSON. It is easy to understand that the MongoDB database stores various JSON(BSON).
The basic concept
- Database database
- An array collection
[{},{},{}]
- Document object document
Similar to records in SQL, a document object {} is a record
A database consists of multiple collections, and a collection contains multiple document objects.
Document manual
The website www.mongodb.com/
Official website manual docs.mongodb.com/manual/
Novice tutorial www.runoob.com/mongodb/mon…
2. Install & Start
Download and install www.mongodb.com/try/downloa…
The current version is 4.4.6
Add environment variables to the system after the installation is complete
Create a db folder in the create Data folder on drive C
Enter Mongod in CMDOpen another CMD belonging to Mongo
To summarize
- Start the mongodb server:
mongod
- Change the default port:
Mongod --port New port number
- Default mongodb port: 27017
- Set the mongodb database storage path:
Mongod -- dbpath path
- Connect to mongodb database:
mongo
MongoDB can be used graphically using MongoDB Compass
Download address www.mongodb.com/try/downloa…
Use 3.
3.1 Basic Usage
Show DBS or show databases: view all databases
Use XXX: switch to the specified database
Db: view the database of the current operation
Show Collections: View all collections in the current database
3.2 DATABASE CRUD Operations
Insert datainsert
Insert a piece of data
db.collectionName.insertOne( {name:'liu'})Copy the code
Db represents the database of the current operation
CollectionName represents a collection of operations. If there is none, it is automatically created
Inserted documents that do not manually provide an _ID attribute are automatically created
② Insert multiple pieces of data
db.collectionName.insertMany( [ {name:'ykyk'}, {name:'ykyk123'}])Copy the code
It needs to be wrapped in array
③ Universal API [can insert one or more] :
db.collectionName.insert()
Copy the code
Visual pages are also easy to use
Query datafind
db.collectionName.find()
Copy the code
Query collection all documents, that is, all data. The query returns the entire array object. There’s an object wrapped around the outermost layer.
Conditions of the query
db.collectionName.find({name:"hhh"})
Copy the code
The result is an array, followed by the index subscriptFind the first one
db.collectionName.findOne()
Copy the code
Returns the first object in the queried array of objects (returns the object)
Query the number of files db.collectionName.count() or db.collectionname.length () Collects the number of files
Note:
> db.students.find({_id:222}).name / / error
> db.students.findOne({_id:222}).name / / right
Copy the code
- Mongodb supports queries directly from property values of embedded documents
{
name:'ykyk'.hobby: {movies: ['movie1'.'movie2'].cities: ['zhuhai'.'chengdu']
}
}
db.users.find({hobby.movies:'movie1'}) / / error
db.users.find({"hobby.movies":'movie1'})// The attribute name of the query must be quoted
Copy the code
- Use of query operators
The comparison operator gt greater than gt greater than Gte greater than or equal to lt less than lt less than lt less than lt less than lte Less than or equal to ne Not equal to NE Not equal to Ne Not equal to eq Is another way of writing $or or
/ / is more than 200
db.users.find({num: {$gt:200}})
// Greater than 200 and less than 300
db.users.find({num: {$gt:200.$lt:300}})
// Greater than 300 or less than 200
db.users.find(
{
$or:[
{num: {$gt:300}},
{num: {$lt:200}}}])Copy the code
- Paging query
Db. The users. The find (). Skip (page -1* Number of items per page). Limit (number of items per page)Copy the code
db.users.find().limit(10) // The first 10 entries
db.users.find().skip(50).limit(10) // Skip the first 50 columns, i.e. 61-70, i.e., page 6
Copy the code
- 【 sort 】find Query results are sorted in ascending order by default
// 1 indicates ascending order and -1 indicates descending order
db.emp.find().sort({sal:1})
// Sort by ascending order of sal. If the same sal is encountered, sort by descending order empno
db.emp.find().sort({sal:1.empno: -1})
Copy the code
Note: Skip,limit, and sort can be called in any order, resulting in sort first, skip, and limit last
Set the projection of the query results, that is, filter out only the fields you want
// Only the ename field is displayed in the matched document
db.emp.find({},{ename:1._id:0})
Copy the code
Query through the visual interface
Modify the dataupdate
Replace the entire document
db.collectionName.update(condiction,newDocument)
Copy the code
$set,$unset,$push,$addToSet
db.collectionName.update(
// Query conditions
{_id:222},
{
// Modify the corresponding attribute
$set: {name:'ykky'.age:21
}
// Delete the corresponding [attribute]
$unset: {gender:1 // The value of 1 can be changed to any other value without any impact}})Copy the code
Update is equivalent to updateOne() by default, which means that only the first updateMany() can be used to change all matched documents
db.students.updateMany(
{name:'ykky'},
{
$set: {age:21.gender:222}})Copy the code
Add data to an array
db.users.update({username:'yk'}, {$push: {"hobby.movies":'movie4'}})
// If the data already exists, it will not be added
db.users.update({username:'yk'}, {$addToSet: {"hobby.movies":'movie4'}})
Copy the code
The increment and decrement operator $inc
// let num increment by 100
{$inc: {num:100}}
// let num decrease by 100
{$inc: {num: -100}}
// Give an increase of 400 to employees earning less than 1000
db.emp.updateMany({sal: {$lt:1000}}, {$inc: {sal:400}})
Copy the code
Delete the dataremove
[Generally not deleted]
db.collectionName.remove()
Copy the code
Remove removes all matching documents by default. The equivalent of deleteMany ()
Remove can add a second argument to remove only the first matched document. This is the same thing as deleteOne()
db.students.remove({name:'ykky'.true})
Copy the code
db.collectionName.deleteOne()
db.collectionName.deleteMany()
Copy the code
Delete all data
db.students.remove({})
Copy the code
Poor character, internal is in the deletion of documents one by one. Delete the entire collection for efficiency.
Delete the collection
db.students.drop()
Copy the code
Deleting a Database
db.dropDatabase()
Copy the code
Note: To delete attributes of a document, use update.
The remove and delete series delete entire documents
If the condition to be deleted is an inline attribute:
db.users.remove({"hobby.movies":'movie3'})
Copy the code
4. Relationships between documents
One to one
Embody one-to-one relationships through embedded documentation
One to many/many to one
[User] – [Order] Each order data saves the user’S ID with an attribute
db.users.insert([
{_id:100.username:'yk'},
{_id:101.username:'ykyk'}
])
db.orders.insert([
{list: ['apple'.'banana'].user_id:100},
{list: ['apple'.'banana2'].user_id:100},
{list: ['apple'].user_id:101}])Copy the code
Query all orders of YK:
1 Obtain the ID of yk
var user_id=db.users.findOne({name:'yk'})._id;
Copy the code
② Query the corresponding order from the order set according to the ID
db.orders.find({user_id:user_id})
Copy the code
Many to many
[Commodity] – [Category]
- Each item data holds multiple category ids with one attribute
- Each category data holds multiple item ids with one attribute
【 Teacher 】- 【 Student 】
db.teachers.insert([
{
_id:100.name:'yk'
},
{
_id:101.name:'ykyk'
},
{
_id:102.name:'ykky'
}
])
db.students.insert([
{
_id:1000.name:'jun'.tech_ids: [100.101] {},_id:1001.name:'jun2'.tech_ids: [102]}])Copy the code
5. mongoose
Chinese document www.mongoosejs.net/
Suggested that English document mongoosejs.com/docs/guide. below…
5.1 introduction
- Before we are through the shell to complete the various operations of the database, in the development of most of the time we need to complete the operation of the database through the program
- Mongoose is a module that allows us to operate MongoDB through Node
- Mongoose is an object Document Model (ODM) library that further optimizes and encapsulates Node’s native MongoDB module with additional functionality
- In most cases, it is used to apply structured schemas to a MongoDB collection and provides benefits such as validation and type conversion
- Mongoose is a JS library in NodeJS dedicated to operating mongodb databases
Advantages of Mongoose: 1. You can create a Schema for the document. 2. Objects/documents in the model can be validated 3. Data can be typed into the object model 4. Middleware can be used to apply business logic hooks 5. Easier than Node’s native MongoDB driver
- Objects in Mongoose:
Schema
Schema object (used to constrain the structure of the document)Model
Model objects (collections in mongodb)Document
Document objects (that is, documents in mongodb)
5.2 installation
npm i mongoose
Copy the code
5.3 Connecting and Disconnecting the Database
// 1. Introduce mongoose
const mongoose = require("mongoose");
2. Connect to the mongodb database
mongoose.connect("mongodb://localhost/admin", {
useNewUrlParser: true.useUnifiedTopology: true});// 3. Monitor the connection status of the mongodb database
// Bind the database connection success event
mongoose.connection.once("open".() = > {
console.log("Database connection successful!");
});
// Bind database connection failure event
mongoose.connection.once("close".() = > {
console.log("Database disconnected");
});
// 4. Disconnect the database (generally not necessary) [Generally only need to connect once, will not disconnect, unless manually disconnect]
mongoose.disconnect();
Copy the code
5.4 Creating Schema Objects and Model Objects
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/admin", {
useNewUrlParser: true.useUnifiedTopology: true}); mongoose.connection.once("open".() = > {
console.log("Database connection successful!");
});
const Schema = mongoose.Schema;
// Create a Schema object
const stuSchema = new Schema({
name: String.age: Number.gender: {
type: String.default: "female",},address: String});// Create Model objects from Schema
// Model represents a collection in the database
// mongoose.model(modelName, schema)
const StuModel = mongoose.model("student", stuSchema);
Copy the code
5.5 Add, delete, check, and modify Model objects
Add operationcreate
Create one or more documents and add them to the database
Model.create(doc(s), [callback])
Copy the code
parameter
doc(s)
It can be a document object or an array of document objectscallback
The callback function that is called when the operation is complete
// Insert a document into the database
// StuModel.create(doc, err=>{})
StuModel.create(
{
name: "YK".age: 18.gender: "male".address: "WuHu",},(err) = > {
if(! err) {console.log("Insert successful!"); }});Copy the code
Mongoose automatically pluralizes the set names
UserModel.create({ user_id: 100.name: "ykyk" }, function (err) {
if(! err) hui{console.log("Insert successful");
} else {
console.log(err); }});let data = [
{ user_id: 101.name: "yk1".age: 19 },
{ user_id: 102.name: "yk2"},]; UserModel.create(data,function (err) {
console.log(arguments[1]); // The second value represents the added document object, which is an array
});
Copy the code
Another way to add data is by new and then Save
const u = new User({
name:'ykJun'.age: 18}); u.save(err= >{
if(err){
console.log(err);
return;
}
console.log('success');
});
Copy the code
Query operationfind
Model.find(conditions,[projection],[options],callback)
Model.findOne(conditions,[projection],[options],callback)
Model.findById(conditions,[projection],[options],callback)
Copy the code
parameter
conditions
: Indicates the query conditionprojection
: projection{ name: 1, gender: 1, _id: 0 }
或'name gender -_id'
options
: Query options{ skip: xx, limit: xx }
callback
: The result of the query is returned by the callback function, which returns the array
UserModel.find({}, function (err, data) {
console.log(data);
});
UserModel.find(
{ name: /yk/i },
"name gender -_id",
{ skip: 2.limit: 1 },
function (err, data) {
console.log(data); // Returns an array of document objects});Copy the code
FindById returns the Document object Document which is an instance of Model
findById
UserModel.findById("5f9fbfba14319e492c0f5bc4".function (err, data) {
console.log(data);
console.log(data instanceof UserModel); //true Returns a document object that is an instance object of the model object (i.e., the collection)
});
Copy the code
Query the number of documents
UserModel.count({}, function (err, count) {
console.log(count);
});
Copy the code
Modify the operatingupdate
Model.update(conditions,[doc],[options],callback)
Model.updateMany(conditions,[doc],[options],callback)
Model.updateOne(conditions,[doc],[options],callback)
Model.replaceOne(conditions,[doc],[options],callback)
Copy the code
parameter
- Conditions Query conditions
- Doc Modified document object
- Options Configuration parameters
{multi: true}
- Callback callback function
UserModel.updateOne({ name: "yk" }, { $set: { age: 22}},(err,data) = > {
if(! err) {console.log("Modified successfully"); }});Copy the code
Delete operationremove
model.remove(conditions,callback)
model.deleteOne(conditions,callback)
model.deleteMany(conditions,callback)
Copy the code
UserModel.remove(
{
name: "yk",},(err, data) = > {
console.log("Deleted successfully"); });Copy the code
note
Document corresponds to the collection Document, Document is an instance of Model and the result of the query from Model is Document
You can also handle the operation database through Document
const stu = new StuModel({
name: 'ykykyk'.age: 19
})
console.log(stu)
stu.save()
StuModel.findOne({}, (err, doc) = > {
if(! err){ doc.update({$set: {age:22}}, err= > {
if(! err) {console.log('Modified successfully'); }}}// There are many other ways
// get()
// set()
// toObject()
});
Copy the code
5.6 Modular Processing
- Create a separate database connection file
dbconncet.js
const mongooes = require("mongoose");
mongooes.connect("mongodb://localhost/mongooes_test", {
useNewUrlParser: true.useUnifiedTopology: true}); mongooes.connection.once("open".function () {
console.log("Connection successful");
});
Copy the code
- Create a model object file for each collection
xxxModel.js
const mongooes = require("mongoose");
const Schema = mongooes.Schema;
const userSchema = new Schema({
user_id: String.name: String.age: Number.gender: {
type: Number.default: 0,}});// Define the model
const UserModel = mongooes.model("user", userSchema);
module.exports = UserModel;
Copy the code
- In the final document
index.js
To import database connection files and create model files
require("./dbconncet");
const UserModel = require("./models/userModel");
UserModel.findOne({}, function (err, docs) {
if(! err) {console.log(docs); }});Copy the code