takeaway

Juejin. Cn/post / 684490… Egg – From Entry to Entry (1)

Juejin. Cn/post / 684490… Egg – From Entry to Entry (ii)

1 Installation and Configuration

1.0 introduction

MongoDB is an open source database system based on distributed file storage written in C++ language. Adding more nodes can ensure server performance under high load conditions. MongoDB aims to provide scalable, high-performance data storage solutions for WEB applications. MongoDB stores data as a document. The data structure consists of key=>value pairs. MongoDB documents are similar to JSON objects. Field values can contain other documents, arrays, and document arrays

1.1 MAC Installation Tutorial

1.1.1 to install homebrew

Check the official website for homebrew installation. After the installation is complete, enter the following command in the terminal to update the Package database of Homebrew

brew update
Copy the code

Brew update update brew version library, brew outdated check the outdated libraries and applications, brew upgrade upgrade outdated libraries and applications, brew cleanup call out outdated libraries and applications

1.1.2 installation mongo

Install mongodb using Homebrew and type in the MAC terminal

cd / 
Copy the code
brew install mongodb
Copy the code

To view installation information

brew info mongodb
Copy the code

Check the mongodb version

mongo --version
Copy the code
 which mongod
Copy the code

/usr/local/bin/mongod

If so, the installation is successful

Start the service

sudo mongod
Copy the code

1.2 Manually Deploying the Server

1.2.1 Downloading the Installation Package

Wget HTTP: / / http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.2.tgzCopy the code

After the download, decompress the package

Tar ZXF mongo - Linux - i686-1.8.2. TGZCopy the code

1.2.2. Installation preparations

Move mongodb to the /usr/local/server/mongdb folder

Mv mongo - Linux - i686-1.8.2 / usr /local/mongodb
Copy the code

Create database folders and log files

mkdir /usr/local/mongodb/data
touch /usr/local/mongodb/logs
Copy the code

1.2.3. Set automatic startup upon startup

Add the mongodb startup project to rc.local to ensure that mongodb starts at server startup

echo "/ usr/local/mongo/bin/mongod -- dbpath = / usr/local/mongo/data - the logpath = / usr/local/mongo/logs logappend - auth - - port = 27017" >> /etc/rc.local
Copy the code

1. Start the mongo

CD Go to the bin folder in the mongodb directory to start mongodb

The following is a permission required login method, user connection requires a user name and password

/usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data --logpath=/usr/local/mongodb/logs --logappend  --auth  --port=27017 --fork
Copy the code

This one does not require a password (not recommended)

/usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data --logpath=/usr/local/mongodb/logs --logappend  --port=27017 --fork
Copy the code

1.3 Complete the pagoda with one key

1.4 Setting a Password

1.4.1 Go to the bin directory of the installation path

cd /www/server/mongodb/bin
Copy the code

1.4.2 Enter mongo to go to the mongodb environment

mongo
Copy the code

1.4.3 Switching to the Admin Database

use admin
Copy the code

1.4.4 Setting a Password for admin

  • User: the user name
  • PWD: indicates the user password
  • Roles: Used to set user permissions, such as read, read, and so on
db.createUser({user: 'root'.pwd: 'admin_mima', roles: ['root']})
Copy the code

1.4.5 Verifying whether the database is added successfully, db.auth(User name, password)

db.auth('root'.'admin_mima') 
Copy the code

If ‘1 ‘is returned, authentication succeeds; if’ 0 ‘is returned, authentication fails.


1.4.6 Create a new database, such as asGiant

use asGiant
Copy the code

1.4.7 Next, add a user to the asGiant library and grant permissions.

db.createUser({ user: 'aaaa'.pwd: 'graphql_mima', roles: [{ role: 'readWrite', db: 'asGiant'}]})Copy the code

Create a CCCC user with read and write privileges db represents the name of the database that the user operates on.

  • Read: Allows the user to Read the specified database
  • ReadWrite: allows users to read and write specified databases
  • DbAdmin: allows users to perform administrative functions in a specified database, such as index creation, deletion, viewing statistics, or accessing system.profile
  • UserAdmin: allows users to write to the System. users collection and to create, delete, and manage users in the specified database
  • ClusterAdmin: Available only in the Admin database, it grants the management rights to all sharding and replication set-related functions.
  • ReadAnyDatabase: only available in the admin database, granting the user read permission for all databases
  • ReadWriteAnyDatabase: This parameter is available only in the admin database and is granted read and write permissions to all databases
  • UserAdminAnyDatabase: Only available in the admin database, granting the user the userAdmin permission for all databases
  • DbAdminAnyDatabase: only available in the admin database, giving the user the dbAdmin permission for all databases.
  • Root: available only in the admin database. Super account, super permission

1.4.8 Enabling Secure Login

When all is said and done, restart mongodb and enable secure login by adding –auth

mongod --dbpath /www/server/mongodb/data --auth
Copy the code

If you are installing manually, do the following

Mongodb, mongodb default access control is not enabled, we use the –auth parameter to restart the Mongod service.

Mongod –dbpath path to the database directory –auth

mongod --dbpath usr/local/mongodb/bin --auth
Copy the code

Once enabled, users must specify a username and password to connect to Mongod.

If you’re using a pagoda with one click

You can do this by modifying the mongodb configuration file

Modified to

net:
  port: 27017
  bindIp: 0.0.0.0
 
#operationProfiling:
#replication:
# replSetName: bt_main
security:
  authorization: enabled
  javascriptEnabled: false
Copy the code
  • Change bindIp to 0.0.0.0 to allow extranet access
  • Change authorization to Enabled. Enable authentication. Restart mongodb

1.5 Releasing Ports

2 Tool Connection

2.1 Downloading the Robo 3T

Creating a connection

Click on the test

The installation is complete

2.2 Connecting to an Encrypted Database

xxx.db(‘mongodb://your name: your pwd@ip:27017/asgiant’); Your name: indicates the user name. Your PWD: indicates the password

3 Data backup and restoration

After auth authentication is enabled for the mongodb database, dump cannot be used directly and the corresponding account password must be provided as follows

Mongodump -h 127.0.0.1:27017-d asGiant -u 'myz' -p '123456' -o /usr/local/mongodb/dump
Copy the code

-h address -d Database name -u User name -p Password -o Output address –authenticationDatabase admin Database for authenticating an account

The mongorestore command script syntax is as follows:

mongorestore -h <hostname><:port> -d dbname <path>
Copy the code
  • **–host <:port>, -h <:port> : **MongoDB server address. The default value is localhost:27017
  • **–db, -d: ** The name of the database instance to be restored, for example: test, can be different from that of test2
  • **–drop: ** When restoring data, delete the current data first and then restore the backup data. That is to say, after recovery, after backup add modified data will be deleted, use with caution!
  • **mongorestore: **mongorestore Sets the last parameter of the backup data location, such as /usr/local/mongodb/dump. You cannot specify both the –dir and –dir options. –dir also sets the backup directory.
  • **–dir: ** Specify the backup directory you cannot specify both the –dir option.
mongorestore -h localhost:27017 -d asGiant -c user --dir /usr/local/mongodb/dump -u myz -p 12346
Copy the code

mongodump -u root -p 123456

mongorestore  -u root -p 123456

4 an egg – mongoose configuration

4.1 installation

$ npm install egg-mongoose --save
Copy the code

4.2 configuration

Change the configuration file {workplace}/config/plugin.js in the Egg project to enable the egg-Mongoose plugin:

exports.mongoose = {
  enable: true,
  package: 'egg-mongoose'};Copy the code

4.3 Egg connects to Mongoose

Add attributes to the config item config in the configuration file {workplace}/config/default.js in the Egg project

config.mongoose = {
    url: process.env.EGG_MONGODB_URL || 'mongo: / / 127.0.0.1 / website'.options: {
      server: {
        poolSize: 40,}}};Copy the code

Connection methods

 config.mongoose = {
    client: {
      url: 'mongodb:// account: password @server: port/library name '.options: {},}};Copy the code

Design the database model

5.1 Define the model, that is, the data table

Define the data table in {workplace}/app/model/article.js

'use strict';
module.exports = app= > {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const RoleSchema = new Schema({
    role: {
      type: String.index: {
        unique: true,},// This field is unique
      require: true./ / mandatory
    },
    roleName: {
      type: String.require: true,},/ / note
    note: {
      type: String.require: true,}});return mongoose.model('Role', RoleSchema, 'role');
};

Copy the code

5.2 Data Types

The data type
Number digital
String string
Boolean Boolean value
ObjectId The object ID
Array An array of
Date The date of
Buffer binary
Mixed Mixed type

6 Adding Data

this.ctx.model.Article.create(post,callback);
Copy the code

Note: Post is a JSON data structure, and callback is a callback function after an operation

7 Querying Data

7.1 Get all data, return is an array

this.ctx.model.Article.find()
Copy the code

7.2 Get a data, return is an object

this.ctx.model.Article.findOne()
Copy the code

7.3 Conditional Query

this.ctx.model.Article.find(conditions,callback);
Copy the code

There are several types of condition

7.3.1 Querying Data Based on Specific Data

this. CTX. Model. The Article. The find ({_id:5c4a819fb87ba4002a47bc4f,title:"123"},callback);
Copy the code
  • The result whose _id is 5C4a819fb87ba4002a47bc4f and title is 123 is returned

7.3.2 Conditional Query

“$lt” Less than
“$lte” Less than or equal to
“$gt” Is greater than
“$gte” Greater than or equal to
“$ne” Is not equal to
this. CTX. Model. The Article. The find ({" sort ": {$get:18 , $lte:30 });
Copy the code
  • Returns the result of a sort greater than or equal to 18 and less than or equal to 30 in the Article table

7.3.3 OR Query OR

“$in” One key corresponds to multiple values
“$nin” Inversely, a key does not correspond to a specified value
“$or” Multiple conditions match, can be nested $in use
“$not” Inversely, search for documents that do not match a particular schema
this.ctx.model.Article.find({"title": {$in: [20.21.22."haha"]});Copy the code
  • Returns the result of title equals 20 or 21 or 21 or “haha” in the Article table
this.ctx.model.Article.find({"$or": [{"age":18}, {"name":"wxw"}}]);Copy the code
  • Returns age = 18 or name = “WXW” in Article table

7.3.4 Type Query ($EXISTS Condition)

this.ctx.model.Article.find({name: {$exists: true}},function(error,docs){
  // Returns all results in the Article table with the name attribute
});
Copy the code
this.ctx.model.Article.find({telephone: {$exists: false}},function(error,docs){
  // Returns all results in the Article table that do not have the telephone attribute
});
Copy the code

7.3.5 Matching regular Expression Queries

MongoDb uses a Prel compatible regular expression library to match regular expressions

this.ctx.model.Article.find( {"name" : /joe/i});Copy the code
  • Returns the result in the Article table whose name is Joe, ignoring case

7.3.6 Querying an Array

this.ctx.model.Article.find({"array":10});Copy the code
  • Array: [1,2,3,4,5,10] is matched
this.ctx.model.Article.find({"array[5]":10});Copy the code
  • Array: [1,2,3,4,5,10] is matched
this.ctx.model.Article.find({"array": [5.10]});
Copy the code
  • Returns a query in the Article table that matches both 5 and 10 in an array
this.ctx.model.Article.find({"array": {$size : 3}});Copy the code
  • Returns a query in the Article table that matches an array of length 3
this.ctx.model.Article.find({"array": {$slice : 10}});Copy the code
  • Returns an Article table query that matches the first 10 elements of an array
this.ctx.model.Article.find({"array": {$slice :  [5.10]}});Copy the code
  • Returns the Article table query matching the 5th through 10th elements of the array

7.3.7 where

It allows you to execute any Javacript statement as part of the query, and if the callback returns true the document is returned as part of the result

this.ctx.model.Article.find( {"$where" :  "this.x + this.y === 10"});this.ctx.model.Article.find( {"$where" : " function(){ return this.x + this.y ===10; }"})Copy the code
  • Where this is the data in the data table, the above returns all data in the Article table for attribute x+ attribute y=10

8 Deleting Data

this.ctx.model.Article.remove(conditions,callback);
Copy the code

Eg: {_id: 5C4a819fb87ba4002a47bc4f} find the data whose _id is 5C4a819fb87ba4002a47bc4f. Callback is the callback function after the operation is successful

9 Updating Data

9.1 Updating Data

this.ctx.model.Article.update(conditions, update, callback)
Copy the code
  • Parameter 1: query condition, parameter 2: update object, you can use MondoDB’s update modifier

Note: Conditions are the same as described in the query data

9.2 Update: Indicates the update object

let post = {
    wid: '5c492c57acbe363fd4824446'.column: [ 'news'].titleHead: ' '.img: ' '.isAbstract: 'false',}this.ctx.model.Article.update({ _id: '5c4a819fb87ba4002a47bc4f ' }, post)
Copy the code
  • Query the Article table for the specific _ID and update the attributes contained in the POST.

Update Uses MondoDB’s update modifier in the following scenarios

9.2.1 “$inc” add-subtract modifier, only for numbers

this.ctx.model.Article.update({"age":22}, {$inc: {"age":1}});Copy the code
  • Find the document where age=22 and change the document’s age value to increase by 1

9.2.2 ‘$set’ specifies the value of a key and creates it if it does not exist. It can be any MondoDB supported type.

this. CTX. Model. The Article. The update ({_id:5c4a819fb87ba4002a47bc4f }, { $set: { isDelete: true}});Copy the code
  • Soft delete table 5C4A819FB87BA4002a47BC4f, find specific _ID data, add or modify isDelete attribute

9.2.3 Reverse “$unset” and delete a key

this.ctx.model.Article.update({age:22}, {$unset: {age:18}});Copy the code
  • The age key does not exist

9.2.4 ‘$push’ creates an array member for a key that does not exist

this.ctx.model.Article.update({name:'wxw'}, {$push: {array:10}});Copy the code
  • Returns the data in the Article table whose name is WXW, and adds an array key of type array with a member 10

9.2.5 ‘$addToSet’ adds an element to the array, not if it exists

this.ctx.model.Article.update({name:'wxw'}, {$addToSet: {array:10}});Copy the code
  • Returns data from Article table whose name is WXW. Array has 10 so it will not be added

9.2.6 ‘The push modifier can be used to insert multiple values

this.ctx.model.Article.update({name:'wxw'}, {$push: {array: {$each: [1.2.3.4.5]}}});Copy the code
  • Select * from Article where name is WXW. Array: [10,1,2,3,4,5]

9.2.7 ‘$pop’ removes an element from the end of the array

this.ctx.model.Article.update({name:'wxw'}, {$pop: {array:1}});Copy the code
  • Array: [10,1,2,3,4,5]; array: [10,1,2,3,4];
  • Tip: Change 1 to -1 to remove the header element

9.2.8 ‘$pull’ removes the specified element from the array

this.ctx.model.Article.update({name:'wxw'}, {$pull: {array:10}});Copy the code
  • Return the Article table with name WXW, and delete it when it matches 10 in array.

10 Sort (sort)

this.ctx.model.Article.sort({ isSetTop: - 1.sort: 1.editTime: - 1 });
Copy the code
  • Sort the data in the Article table, descending first by “isSetTop”, then by “sort”, and finally by “editTime”

Note: The key name in the data corresponding to the key. The value indicates the sorting direction, which is 1 ascending and -1 descending.

11 Limit the number of results returned (limit)

this.ctx.model.Article.limit(3);
Copy the code
  • Returns the first three pieces of data from the Article table

12 Skip the first 3 documents and return to the rest (skip)

this.ctx.model.Article.skip(3);
Copy the code
  • Return the data in the Article table, skipping the first three and returning the remaining data

Note: the last three methods are combined for paging queries

this. CTX. Model. The Article. The find ({_id:5c4a819fb87ba4002a47bc4f }).skip(pageSize * (pageNum - 1)).limit(parseInt(pageSize)).sort({ isSetTop: - 1.sort: 1.editTime: - 1 });
Copy the code
  • Where pageSize and pageNum are dynamic transfer data, return the data on the pageNum page of Article table with the specified _ID in the condition that the data on each page is pageSize, descending by “isSetTop”, ascending by “sort”, Finally sort by “editTime” in descending order.