当前位置:网站首页>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()
边栏推荐
- Interpretation of new plug-ins | how to enhance authentication capability with forward auth
- proxy
- Call the random function to generate 20 different integers and put them in the index group of institute a
- Memory partition model
- proxy
- Make up the weakness - Open Source im project openim about initialization / login / friend interface document introduction
- Swap two numbers
- GUI+SQLServer考试系统
- 安信证券排名第几位?开户安全吗?
- No manual prior is required! HKU & Tongji & lunarai & Kuangshi proposed self supervised visual representation learning based on semantic grouping, which significantly improved the tasks of target dete
猜你喜欢

Web3去中心化存储生态图景

基於Kubebuilder開發Operator(入門使用)

进军AR领域,这一次罗永浩能成吗?

5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?

【从删库到跑路】JDBC 完结篇(一天学完系列!!学完赶紧跑!)
Scala 基础 (二):变量和数据类型

R329 (maix-ii-a (M2A) data summary

The first open source MySQL HTAP database in China will be released soon, and the three highlights will be notified in advance

Junit单元测试

TCP congestion control details | 1 summary
随机推荐
Discover K8E: minimalist kubernetes distribution
JS tutorial - printing stickers / labels using the electronjs desktop application
防火 疏散 自救…这场安全生产暨消防培训干货满满!
并发编程整体脉络
[graduation season] a word for graduates: the sky is high enough for birds to fly, and the sea is wide enough for fish to leap
Stm32h7b0 replaces the h750 program, causing the MCU to hang up and unable to burn the program
Programmer interview guide - self introduction
5g is not flat and 6G is restarted. China leads wireless communication. What is the biggest advantage of 6G?
Memory partition model
构造函数和析构函数
Redis migration (recommended operation process)
[机缘参悟-31]:鬼谷子-抵巇[xī]篇-危机是危险与机会并存
Apache APIs IX has the risk of rewriting the x-real-ip header (cve-2022-24112)
Which position does Anxin securities rank? Is it safe to open an account?
QT 5.9.8 installation tutorial
电路中缓存的几种形式
NFT 交易市场社区所有化势不可挡
5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?
[from deleting the database to running] the end of MySQL Foundation (the first step is to run.)
I regard it as a dry product with a monthly income of more than 30000 yuan for sidelines and more than 10000 yuan for novices!