Mongodb notes

Application scenarios of mongodb
Mondodb is a distributed file storage database. At the same time, it is also a NoSQL database. It mainly provides scalable high-performance solutions for web applications. Mongodb is a memory database, so there will be data loss problems. Therefore, it is not possible to strictly guarantee that the data will not be lost in mongodb, which is the ultimate storage solution;
  • Website real time data: log, user behavior, timeline
  • Data cache: the cached data is temporary and should be saved in the relational database
  • Large size low value data: picture file or video file
  • High scalability scenarios: scenarios where machines are arbitrarily increased or decreased
  • Object or JSON storage
  • Highly transactional system: financial system
  • Highly confidential user data
  • Structured association query requires very high requirements: such as report system
Mongodb terminology
mysql mongoDB explain
DataBase DataBase database
table collection Table or set
Row Dcoument data row
Colum Field Data column, field
index index Indexes
Table join I won’t support it Table Association
PremaryKey ObjectID Primary key
data type
data type explain give an example
Null Null value {x: null}
Boolean Boolean value {x: true}
Integer integer {x: 1}
Double Floating point number {x: 3.14}
String character string {X: “string”}
ObjectID Object ID {x: ObjectID()}
Date time {x: new Date()}
TimeStamp time stamp {x: 142343214123}
Array array {x: [“a”,”b”]}
Object Embedded document {x: {“a”,”b”}}
Installation and startup of single mongodb
  1. Download the tar package from the official website and unzip it
  2. Create data data directory and logs log directory
  3. create profile mono.conf The contents are as follows:
  4. Configure the environment variable: VI / etc / profile, and add export path = $path / mongodb / mongodb linux-x86 in the last line_ 64-debian92-4.0.3/bin, and then execute source / etc / profile
  5. Use. / bin / mongod – F/ mongo.conf start-up
  6. Run. / Mongo to see if you can enter the program
mongo.conf content

Fork = true ා running in the background
bind_ IP = ා allow any IP to connect
Auth = false ා is the connection authorized
Connecting tools


Mongodb architecture

Data writing process

Mongodb notes

Data reading process

Mongodb notes
Mongos is the coordination center of mongod and the channel for interaction between client and server;
Mongod config is the configuration center
Mongod is a database

Spring boot integrates mongodb
  • Add dependency
  • Add relevant configuration in YML file
  • Inject mongotemplate to use
Mongodb syntax
X query people aged 25 and 27
Find out the math scores of all people whose nationality is not South Korea
db.t_ member.find ({country: {$ne: "Korea"}}{_ id:0, name:1 , country:1 }

$in or $Nin
Search for information about students with Chinese or American nationality

Query the information of students whose Chinese score is greater than 85 or English is greater than 90
Add a new key to Chinese students
Find the person whose sex is null

Find out the information of students with "Li" in their names

The difference between $not and $Nin is that $not can be used anywhere, and $Nin is used on sets
Find out the information of the students whose name does not contain "Li"

Query students who like to watch mongod and JS
Query the second book is java learning information

The number of books they like is 4
Find out the students who like more than 4 books
Add size key
Add books and update size

Query more than 3 copies

2 ~ 4 books found in Jim's bookshelf
Find out the last book

Find out the students who have studied in K with a grade
For absolute queries, the order and the number of keys should be exactly the same
Object mode, but there will be errors. Multiple conditions may query multiple objects

Correct way to query $elemmatch of single condition group

Pagination and sorting
1) Limit returns the specified number of items to query the first five pieces of data in the persons document
2) Specify the data span to query the five data after the third data in the persons document
3) Sort 1 is positive and - 1 is reverse

$Inc: only used for numeric type. You can add or subtract the numeric type of the specified key value pair

As a result, the age of Zhangsan was increased by 2
$unset: delete the specified key

$push: array key operation: 1. If there is a specified array, add a value for it; 2. If there is no specified array, then
Create an array key and add a value; 3. If the specified key is not an array type, an error will be reported;
$addtoset: when the specified array has this value, it will not be inserted, otherwise it will be inserted
Will not be added to the array

$Pop: delete the value of the specified array, when value = 1, delete the last value, when value = - 1, delete the first value
The last value was deleted
$pull: delete the value specified by the specified array
$pullall batch delete specified array
If there are more than one Chinese in the array, all of them will be deleted
$: when modifying the specified array, if the array has multiple objects, but only some of them want to be modified, the locator is required:
The combination of $addtoset and $each completes the batch array update operation
Mongodb high availability

Cluster master-slave architecture (m-a-s, a stands for arbitration node, this node does not undertake data storage function, this machine’s hanging point is OK, one of the master-slave can take this role)

Create user command:

Use show roles to view all roles

Config file configuration

In addition to the above configuration, add the following fields:

#Represents the name of the cluster

All three machines are started with the same configuration;

Log in to a machine at will to initialize the cluster

#Using the admin database
use admin

#Make configuration take effect
#View status

Mongodb official recommendation mode (need to use at least 8 servers)

  1. Add the configuration shardsvr = true to the configuration file, configure three machines, configure the same cluster name, start, and then use the above method to make the configuration effective;
  2. Add configsvr = true to the configuration file, configure three machines, and configure the same cluster name. Be careful not to start the same operation as the above one;
  3. Configure the routing node and add the following configuration:

Remove the dbpath and replsset configurations, and start:

./mongos -f /mongodb.cfg
  1. Connect routing nodes for configuration:
#The routing node must be connected here
#Shard001 and shard002 indicate the name of the replica set. When the master node is added to the shard, the
Automatically find the master, standby and decision nodes in the set
use testdb
sh.enableSharding("testdb") #testdb is database name

The idea of the whole architecture is similar to that of ES architecture. Only when the amount of data is really large will it show its role;

Mongodb index

Create index


Create the index and specify the name of the index


What should be paid attention to when using index

  1. Note that the index is created in reverse order of – 1
  2. The creation of index will affect the performance of inserts when improving query performance. For documents that are frequently queried and less inserted, we can consider using index
  3. Attention should be paid to the order of index in accordance with the index
  4. Indexing every key does not necessarily improve performance. Indexing is not everything
  5. When sorting, if it is a large amount of data, you can also consider adding index to improve the sorting performance

unique index

If the same name value is inserted, an error will be reported
#What if there are duplicate values before a unique index is suggested
Eliminate duplicate values

Other operations

#Force queries on established indexes
The last name is the index name. The positive and reverse order is based on the rules for building the index. Otherwise, an error will be reported
#Query index information and query status information
#Bulk and precise index deletion
db.runCommand({dropIndexes : "books" , index:"name_-1"})
db.runCommand({dropIndexes : "books" , index:"*"})
Data import and export

Export the data to the persons in testdb

mongoexport -d testdb -c persons -o D:/persons.json
Exporting documents from other host databases
mongoexport --host --port 37017

Import data (interrupt other operations)

mongoimport --db testdb --collections persons --file d:/persons.json