当前位置:网站首页>Getting started with mongodb
Getting started with mongodb
2022-06-26 16:54:00 【Comrade Xiaoqiang】
One 、MongoDb Architecture of
Summary :
- NoSql The concept of
- NoSql Application scenarios of
- MongoDb The logical composition of
1、NoSql The concept of
NoSQL(NoSQL = Not Only SQL ), meaning “ not only SQL”, In the early days of the Internet, most of our data were stored in relational databases . Its characteristic is the standard data structure ( Predefined patterns )、 Strong oneness 、 Tables are associated with each other through foreign keys , These characteristics make our data management more clear and rigorous , But with the development of the Internet, the data is growing explosively. We need better flexibility and faster speed for the database . This is it. NoSql doable . It does not require a predefined schema , There is no primary foreign key Association 、 Support fragmentation 、 Support replica .
NoSql The classification of :
Key value (Key-Value) Storage database
This kind of database mainly uses a hash table , This table has a specific key and a pointer to a specific data .Key/value The model is for IT The advantage of the system is simplicity 、 Easy to deploy . But if DBA When only some values are queried or updated ,Key/value It's inefficient . For example :Tokyo Cabinet/Tyrant, Redis, Voldemort, Oracle BDB.
Column store database .
This part of database is usually used to deal with the massive data of distributed storage . The bond still exists , But they feature multiple columns . These columns are arranged by the families of columns . Such as :Cassandra, HBase, Riak.
Document database
The inspiration of document database comes from Lotus Notes Office software , And it's similar to the first key value store . This type of data model is a versioned document , Semi structured documents are stored in a specific format , such as JSON. Document database can As an upgrade of the key value database , Allows nesting of key values . And the query efficiency of document database is higher than that of key value database . Such as :CouchDB, MongoDb. There are also document databases in China SequoiaDB, Is open source .
graphics (Graph) database
The database of graphic structure is the same as other rows and columns and rigid structure SQL Databases are different , It's using flexible graphic models , And can be extended to multiple servers .NoSQL There is no standard query language in the database (SQL), Therefore, it is necessary to develop data model for database query . many NoSQL Databases all have REST Data interface or query API. Such as :Neo4J, InfoGrid, Infinite Graph.
2、NoSql Application scenarios of
NoSQL The database is applicable in the following cases :
1、 The data model is simple ;
2、 Need more flexibility IT System ;
3、 High requirements for database performance ;
4、 No need for high data consistency ;
- Based on Douban movie, give an example NoSQL Application scenarios of
- Analysis of the basic information of movies
- The relationship between movies and stars is stored
3、MongoDb The logical composition of
Architecture :

Comparison between logical structure and relational database :
Relational database | MongoDb |
database( database ) | database( database ) |
table ( surface ) | collection( aggregate ) |
row( That's ok ) | document( BSON file ) |
column ( Column ) | field ( Field ) |
index( unique index 、 primary key ) | index ( Full-text index ) |
join ( Primary foreign key Association ) | embedded Document ( Nested documents ) |
primary key( Appoint 1 to N A column is used as the primary key ) | primary key ( Appoint _id field As a primary key ) |
aggreation(groupy) | aggreation (pipeline mapReduce) |
Two 、MongoDb Installation configuration and basic commands
Summary :
- mongoDb Version Description
- mongoDb Start parameter description
- client Shell Use and parameter description of
- Basic operations of databases and collections
- mongoDb Community Edition description
Download address :MongoDB Community Download | MongoDB

# download
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.5.tgz
# decompression
tar -zxvf mongodb-linux-x86_64-4.0.5.tgz
2.mongoDb Start parameter description
mongoDb from C++ To write , The downloaded package can be started directly
# Create database directory
mkdir -p /data/mongo
# start-up mongo
./bin/mongod --dbpath=/data/mongo/
Conventional parameters
Parameters | explain |
dbpath | Database directory , Default /data/db |
bind_ip | monitor IP Address , All can be accessed by default |
port | Listening port , Default 27017 |
logpath | Log path |
logappend | Append log |
auth | Is to open the user password login |
fork | Whether the login has been started in the background |
config | Specify profile |
Sample configuration file
vim mongo.conf
Content :
dbpath=/data/mongo/
port=27017
bind_ip=0.0.0.0
fork=true
logpath = /data/mongo/mongodb.log
logappend = true
auth=false
Started in profile mode
./bin/mongod -f mongo.conf
3. client Shell Use and parameter description of
# Start client Connect The default port of this machine
./bin/mongo
# Appoint IP And port
./bin/mongo --host=127.0.0.1 --port=27017
mongo shell It's a js Control desk , It can be executed js Related operations such as :
> 1+1
2
> var i=123;
> print(i)
123
>
4. Basic operations of databases and collections
# view the database
show dbs;
# Switch database
use demo;
# Create databases and collections , Automatically when inserting data Create databases and sets
db.friend.insertOne({name:"wukong",sex:"man"});
# View set
show tables;
show collections;
# Delete the collection
db.friend.drop();
# Delete database
db.dropDatabase();
3、 ... and 、MongoDB CRUD
Summary :
- How to add data
- Data query
- Data modification and deletion
- Full text index query
- How to add data
About Mongodb Description of data insertion
- There is no need to design the model structure in order to add a database , Automatically created when inserting data .
- Different data field structures in the same set can be different
Insert related methods :
// Insert a single bar
db.friend.insertOne({name:"wukong",sex:"man"});
// Insert more than one
db.friend.insertMany([
{name:"wukong",sex:"man"},{name:"diaocan",sex:"woman",age:18,birthday:new Date("1995-11-02")},{name:"zixiao",sex:"woman"}
]);
// Appoint ID
db.friend.insert([
{_id:1,name:"wokong",sex:"man",age:1},
{_id:2,name:"diaocan",sex:"women",birthday:new Date("1988-11- 11")}
])
2、 Data query
Summary :
- Condition based basic query
- $and、$or、$in、$gt、$gte、$lt、$lte Operator
- be based on sort skip limit Method to implement sorting and paging
- nested queries
- Array query
- Array nested query
- Value operation :$in、$gt、$gte、$lt、$lte $all
- Logical operations :$and、$or
Its value is a combination operation of multiple logics , Followed by brackets , Brackets include multiple braces .
Based on specific values
Basic query :
# be based on ID lookup
db.emp.find({_id:1101})
# Find based on attributes
db.emp.find({"name":" ruban "})
# && operation And greater than operation
db.emp.find({"job":" lecturer ","salary":{$gt:8000}})
# in operation
db.emp.find({"job":{$in:[" lecturer "," Customer service department "]}})
# or operation
db.emp.find({$or:[{job:" lecturer " },{job:" Customer service department "}] })
db.friend.find({$or:[{"name":"diaocan"},{age:{$gte:18}}]});
Sorting and paging :
// sort skip limit
db.emp.find().sort({dep:1,salary:-1}).skip(5).limit(2)
nested queries :
# The wrong sample : There is no result
db.student.find({grade:{redis:87,dubbo:90 });
# The wrong sample : There is no result
db.student.find({grade:{redis:87,dubbo:90,zookeper:85} })
# Find based on composite attributes Must contain all its values And the order is from one to
db.student.find({grade:{redis:87,zookeper:85,dubbo:90} })
# Based on the specified value in the composite attribute lookup . notes : The name must be in double quotation marks
db.student.find({"grade.redis":87});
db.student.find({"grade.redis":{"$gt":80}});
Array query :
db.subject.insertMany([
{_id:"001",name:" Chenbatian ",subjects:["redis","zookeper","dubbo"]},
{_id:"002",name:" Zhang Mingming ",subjects:["redis","Java","mySql"]},
{_id:"003",name:" Xiaoyanyan ",subjects:["mySql","zookeper","bootstrap"]},
{_id:"004",name:" Li Guicai ",subjects:["Java","dubbo","Java"]},
])
# There is no result
db.subject.find({subjects:["redis","zookeper"]})
# There is no result
db.subject.find({subjects:["zookeper","redis","dubbo"]})
# Just like nested queries , Must be all values And the order is from one to
db.subject.find({subjects:["redis","zookeper","dubbo"]})
# $all The matching array contains the values of these two items . notes : The order is not required
db.subject.find({subjects:{"$all": ["redis","zookeper"]}})
notes :
# Simplify array queries
db.subject.find({subjects:"redis"})
# Simplify array queries , There is any value in the matching array . And $all Corresponding
db.subject.find({subjects:{$in: ["redis","zookeper"]}})
Array nested query :
# Basic query , All must be queried , And the sequence is from one to
db.subject2.find({subjects:{name:"redis",hour:12} })
# Specify to query the first array Class hours are greater than 12
db.subject2.find({"subjects.0.hour":{$gt:12}})
# Query any account Class hours are greater than 12
db.subject2.find({"subjects.hour":{$gt:12}})
# $elemMatch Element match , Specify that the attribute satisfies , And it does not require the sequence from one to
db.subject2.find({subjects:{$elemMatch:{name:"redis",hour:12}}})
# Any element in the array matches Not limited to the same object
db.subject2.find({"subjects.name":"mysql","subjects.hour":120})
The operator :
- $elemMatch: Perform logical operations on child elements
3、 Modification and deletion of data
db. surface .update( Conditions ,{ Set the value },false,false )
The operator :
- $set : Set the value
- $unset : Delete the specified field
- $inc: Self increasing
$set modify
# Set the value
db.emp.update({_id:1101} ,{ $set:{salary:10300} })
# Self increasing
db.emp.update({_id:1101} ,{ $inc:{salary:200}})
# Based on the conditions Update multiple data
# Only the first item will be updated
db.emp.update({"dep":" Customer service department "},{$inc:{salary:100}})
# Update all Matching conditions
db.emp.updateMany({"dep":" Customer service department "},{$inc:{salary:100}})
$unset Delete field
db.subject2.update({"_id":"001"},{$unset:{"subjects":1}})
Nested array modification :
Operator :
- $addToSet : Add to set ( Commands are case sensitive )
- $push: Push to collection
- $pull: Remove from collection
- $pop: Delete... From the collection Two end non tail elements .
$addToSet: Add to set , Multiple executions do not repeat the insertion
db.subject2.update({"_id":"001"},{$addToSet:{"subjects":{"name":"mongodb","hour":20}}})
$push: Push to collection , Do not judge repetition
db.subject2.update({"_id":"001"},{$push:{"subjects":{"name":"mongodb","hour":20}}})
$pull: The matching element items , Remove all from the collection
db.subject2.update({"_id":"001"},{$pull:{"subjects":{"name":"mongodb","hour":20}}})
# Match only one field
db.subject2.update({"_id":"001"},{$pull:{"subjects":{"name":"mongodb"}}})
$addToSet、$push、$pull Can manipulate arrays , The effect is equivalent to executing the elements in the array multiple times .
db.subject2.update({"_id":"001"},{$addToSet:{"subjects":[{"name":"mongodb","hour":20},{"name":"mongodb2","hour":22}]}})
$pop: Delete... From the collection Two end non tail elements .
# -1 Delete team leader Elements
db.subject2.update({"_id":"001"},{$pop:{"subjects":-1}})
# 1 Delete end of team element
db.subject2.update({"_id":"001"},{$pop:{"subjects":-1}})
notes : The value can only be 1 or -1, Cannot be any other value
$elemMatch Delete column elements based on conditions :
# Delete id=001 in hour Greater than 10 The element of cannot be deleted
db.subject2.update({"_id":"001"},{$pull:{"subjects":{"hour":{$gt:10}}}})
# Use $elemMatch Run operator
db.subject2.update({"_id":"001"},{$pull:{"subjects": {$elemMatch:{"hour":{$gt:10}}} }})
upsert When updating, if the record does not exist , The insert operation will be performed
db.subject2.update({"_id":"009"},{$set:{"name":" Chen Chen "}},true)
Update multiple records :
By default ,update Only a single record will be updated , Update multiple , You need to add a fourth parameter by true, Or use
# Only the first item will be updated
db.subject2.update({},{$set:{"name":" Chen "}},true,false)
# Update all
db.subject2.update({},{$set:{"name":" Chen "}},true,true ,)
# Update all
db.subject2.updateMany({},{$set:{"name":" Chen "}})
Delete :
// Delete based on lookup
db.emp.deleteOne({_id:1101})
// Delete entire collection
db.project.drop()
// Delete Library
db.dropDatabase()
边栏推荐
- Kubecon China 2021 Alibaba cloud special session is coming! These first day highlights should not be missed
- 安信证券排名第几位?开户安全吗?
- STM32F103C8T6实现呼吸灯代码
- C language --- basic function realization of push box 01
- [chat in 5] eight years after graduation, I have been pursuing my dream
- [Error] ld returned 1 exit status
- Stm32h7b0 replaces the h750 program, causing the MCU to hang up and unable to burn the program
- In a bad mood, I just write code like this
- 5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?
- Research on natural transition dubbing processing scheme based on MATLAB
猜你喜欢

Discussion: the next generation of stable coins
![[Error] ld returned 1 exit status](/img/38/ec4645880d4c14e3766fbcabe8ddde.jpg)
[Error] ld returned 1 exit status

Pybullet robot simulation environment construction 5 Robot pose visualization

Teach you to learn dapr - 5 Status management

MS | Xie Liwei group found that mixed probiotics and their metabolites could alleviate colitis

Teach you to learn dapr - 2 Must know concept

对NFT市场前景的7个看法

Research on natural transition dubbing processing scheme based on MATLAB

GUI+SQLServer考试系统

When a programmer is disturbed 10 times a day, the consequences are amazing!
随机推荐
What is the difference between digital collections and NFT
Cloud platform monitoring system based on stm32+ Huawei cloud IOT design
Développer un opérateur basé sur kubebuilder (démarrer)
The student record consists of student number and academic performance. The data of n students have been stored in the a structure array to find out the student record with the lowest performance
[从零开始学习FPGA编程-46]:视野篇 - 集成电路的发展与技术进步
【毕业季】致毕业生的一句话:天高任鸟飞,海阔凭鱼跃
Leetcode 1170. 比较字符串最小字母出现频次(可以,已解决)
Teach you to learn dapr - 4 Service invocation
Data analysis - numpy quick start
Vibrating liquid quantity detecting device
Teach you to learn dapr - 6 Publish subscription
Community ownership of NFT trading market is unstoppable
Codeforces Round #802 (Div. 2)
proxy
COMP5216 Mobile Computing Assignment 1 - Extending ToDoList app
1-12vmware adds SSH function
Discover K8E: minimalist kubernetes distribution
Interpretation of new plug-ins | how to enhance authentication capability with forward auth
安信证券排名第几位?开户安全吗?
Multiply the values of the upper triangular elements of the array by M