当前位置:网站首页>Get started with mongodb
Get started with mongodb
2022-07-07 23:38:00 【Clock in the opposite direction 197】
Catalog
3. Download from the official website
4.1 Start service in command parameter mode
4.2 Start the service in profile mode
9. Document insertion and query
14. Summary of common commands
1. brief introduction
It's a Open source 、 High performance 、 Modeless Document shaped database ,mysql Is a relational database . It is the kind of non relational database that is most like a relational database .
The data format is very loose , Be similar to JSON The format of BSON, It can store complex data types , And more flexible .
MonggoDB Record eleven documents , It consists of a field value pair (field:value) Form a data structure , Be similar to json formation
2. characteristic :
High performance : Support persistence , Index supports faster and longer training
High availability :MongoDB The to tool is called a replica set , It provides automatic failover and data redundancy
High expansion : Fragmentation distributes data across a cluster of machines .( Mass data storage , Service capability level expansion )
Rich query support :B Support rich query language , Supports read and write operations (CRUD), For example, data aggregation 、 Text search and geospatial query, etc .
3. Download from the official website
MongoDB Community Download | MongoDB Download from the official website
https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-5.0.9.zip Download link
Naming specification :X.Y.Z The format of
y An odd number indicates that the current version is the development version , Such as :1.5.2、4.1.13;
4. start-up
4.1 Start service in command parameter mode
Default port 27017
Create a folder to store the database , Created in the root directory data>db Folder
stay bin Under the table of contents Start command :
Start command :ps This --dbpath= The following is the address of the file you want to save in the database
ps: No space after
mongod --dbpath=..\data\db
Successful initialization
4.2 Start the service in profile mode
First write a configuration class
stay bin Write a conf, Write one by one in it mongod.conf
storage:
#The directory where the mongod instance stores its data.Default Value is "\data\db" on Windows.
dbPath: E:\baidu\MongoDB\mongodb-windows-x86_64-4.4.15\mongodb-win32-x86_64-windows-4.4.15\data\db
ps:dbPath The front is empty 4 A space , spot tab Will report a mistake
Start command
stay bin Under the table of contents
mongod -f ../config/mongod.conf
or
mongod --config ../conf/mongod.conf
5.shell Command connection
programme 1: Configure environment variables , It's just path It's equipped with mongodb Of bin Catalog
Then type on the command line :mongo start-up
programme 2: stay bin Start... In the directory Input mongo
6.Linux Command to install
First download the installation package , And import linux Inside
decompression :
tar -xvf mongodb-linux-x86_64-4.0.10.tgz
Move to your own folder
mv mongodb-linux-x86_64-4.0.10 /opt/module/
At this point, it's equivalent to windows The default configuration
Again according to windows Start in the same way establish data,log,config file
Modify the configuration file
systemLog:
#MongoDB The destination for sending all log output is specified as a file
# #The path of the log file to which mongod or mongos should send all diagnostic logging information
destination: file
#mongod or mongos Path to the log file to which all diagnostic logging information should be sent
path: "/mongodb/single/log/mongod.log"
# When mongos or mongod When the instance restarts ,mongos or mongod The new entry is appended to the end of the existing log file .
logAppend: true
storage:
#mongod The directory where the instance stores its data .storage.dbPath Settings only apply to mongod.
##The directory where the mongod instance stores its data.Default Value is "/data/db".
dbPath: "/mongodb/single/data/db"
journal:
# Enable or disable persistent logging to ensure that data files remain valid and recoverable .
enabled: true
processManagement:
# Enable running in the background mongos or mongod The daemons mode of the process .
fork: true
net:
# Service instance binding IP, The default is localhost,115.60.97.40 Server intranet address
bindIp: localhost,115.60.97.40
#bindIp
# Bound port , The default is 27017
port: 27017
7.Docker install
I'll add later
8. Basic use of commands
In front of :mongodb Storage structure of
8.1 Operation of database
use Database name Select and create data and libraries , If the database does not exist, it will be created directly , First create it, then store it in memory
show dbs View the database contents you have permission to view
show databases and show dbs equally
ps:
1. Again MongosDB in , The collection will not be created until the content is inserted !, Create set ( Insert a document record after the data table ), Set will appear
2. The database creation meets the following conditions :
1) It cannot be an empty string 2) Can't contain spaces , spot ,$,/,\, and ( Null character )3) Should be all lowercase 4) most 64 Bytes
db View the database commands currently in use , If no database collection is selected, it will be stored by default test In the database
You can see use The database of
Keep the database :
8.2 Database deletion
db.dropDatabase() Used to delete the persistent database
8.3 Set operations
According to create
db.createCollection(" Collection name ") Create set
show collections View the collection created
db. aggregate .drop() Delete the collection
Implicit creation
Specific in 9, Generally speaking, documents are created directly without
9. Document insertion and query
Insert
Single insertion
db. Collection name .insert( Switch to save It's fine too )(
{json data }
) Insert a single document
Insert more
db.my.insertMany([
{json data },
{json data },
{json data }
]) Insert multiple documents
give an example :
db.comment.insertMany([
{"_id":"1","articleid":"100001","content":" We shouldn't waste the morning on cell phones , Health is very important , A cup of warm water makes you and me happy He .","userid":"1002","nickname":" Forget about the Jianghu ","createdatetime":new Date(),"likenum":NumberInt(1000),"state":"1"},
{"_id":"2","articleid":"100001","content":" I drink cold boiled water on an empty stomach in summer , Drink warm water in winter ","userid":"1005","nickname":" The Iraqi are haggard Haggard ","createdatetime":new Date(),"likenum":NumberInt(888),"state":"1"},
{"_id":"3","articleid":"100001","content":" I drink cold water all the time , Drink in winter and summer .","userid":"1004","nickname":" Jack boat Long ","createdatetime":new Date(),"likenum":NumberInt(666),"state":"1"},
{"_id":"4","articleid":"100001","content":" Experts say you can't eat on an empty stomach , Affect health .","userid":"1003","nickname":" kay scatter ","createdatetime":new Date(),"likenum":NumberInt(2000),"state":"1"},
{"_id":"5","articleid":"100001","content":" Studies have shown that , Just boiled water must not be drunk , Because it's hot mouth .","userid":"1003","nickname":" Caesar ","createdatetime":new Date(),"likenum":NumberInt(3000),"state":"1"}
]);
Inquire about
db. Collection name .find() db. Collection name .find({}) Document query
db.comment.find({" Column ":" value "}) Query the corresponding attribute
give an example :
db.comment.find({"articleid":"100001"})
Conditions of the query
db.comment.find( {" Column ":" value "} ,{_id:1,articleid:0} ) The first column identifies the qualified rows , The second row represents the columns of the query ,0 Means not to show ,1 Presentation display give an example
db.comment.find({"articleid":"100001"},{_id:1,articleid:0})
Delete
db. surface .drop() Delete the collection
give an example
db.comment.drop()
Business
MongoDB Unsupported transaction , But it can use json Grammar use try--catch(){print(e)} Insert failed at prompt
give an example :
try{
db.comment.insertMany([
{"_id":"1","articleid":"100001","content":" We shouldn't waste the morning on cell phones , Health is very important , A cup of warm water makes you and me happy He .","userid":"1002","nickname":" Forget about the Jianghu ","createdatetime":new Date(),"likenum":NumberInt(1000),"state":"1"},
{"_id":"1","articleid":"100001","content":" I drink cold boiled water on an empty stomach in summer , Drink warm water in winter ","userid":"1005","nickname":" The Iraqi are haggard Haggard ","createdatetime":new Date(),"likenum":NumberInt(888),"state":"1"},
{"_id":"3","articleid":"100001","content":" I drink cold water all the time , Drink in winter and summer .","userid":"1004","nickname":" Jack boat Long ","createdatetime":new Date(),"likenum":NumberInt(666),"state":"1"},
{"_id":"4","articleid":"100001","content":" Experts say you can't eat on an empty stomach , Affect health .","userid":"1003","nickname":" kay scatter ","createdatetime":new Date(),"likenum":NumberInt(2000),"state":"1"},
{"_id":"5","articleid":"100001","content":" Studies have shown that , Just boiled water must not be drunk , Because it's hot mouth .","userid":"1003","nickname":" Caesar ","createdatetime":new Date(),"likenum":NumberInt(3000),"state":"1"}
]);
} catch (e) {
print (e);
}
10. Document update
db. aggregate .update(query,update,options) With query Conditions of the query , And modified to update What's in it ,options Is an optional parameter
Overwrite modification
db.comment.update({_id:"6"},{content:NumberInt("10002")}) hold query Change all columns to replace
Partial modification
db.comment.updateOne({_id:"1"},{$set:{articleid:"102"}}) Modify only one column
Bulk changes
db.comment.update({userid:"1003"},{$set:{nickname:" Caesar the great "}},{multi:true})
Yes multi Not set true
Column value growth modification
db.comment.update({_id:"3"},{$inc:{likenum:NumberInt(1)}}) $inc It means to increase by one
11. Document delete
12. Document paging query
db. aggregate .count(query, options) query Indicates the query criteria ,options Additional options for modifying technology
db.comment.count() How many pieces of data to query
db.comment.count({articleid:"100001"}) How many pieces of data are queried by criteria
db.comment.find().limit(2) Before display 2 Data
db.comment.find().limit(2) .skip(2) Show two pieces of data and skip the first two
db.comment.find().sort() Default to _id In ascending order
db.comment.find().sort({userid:1}) With userid In ascending order 1 Expressing ascending order -1 Representation of descending order
13. More complex queries
Fuzzy query
db.collection.find({field:/ Regular expressions /})
Comparison query
db. Collection name .find({ "field" : { $gt: value }}) // Greater than : field > value
db. Collection name .find({ "field" : { $lt: value }}) // Less than : field < value
db. Collection name .find({ "field" : { $gte: value }}) // Greater than or equal to : field >= value
db. Collection name .find({ "field" : { $lte: value }}) // Less than or equal to : field <= value
db. Collection name .find({ "field" : { $ne: value }}) // It's not equal to : field != value
give an example : The number of comments and likes is greater than 700 The record of
db.comment.find({likenum:{$gt:NumberInt(700)}})
Contains the query
db.comment.find({userid:{$in:["1003","1004"]}}) $in Means contained in 1003 and 1004
Conditional connection
intersection $and:[ { },{ },{ } ] see likenum Field is greater than or equal to 700, Less than 2000
db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]})
Combine $or:[ { },{ },{ } ] see userid by 1003 also likenum The field is less than 1000 Of
db.comment.find({$or:[ {userid:"1003"} ,{likenum:{$lt:1000} }]})
14. Summary of common commands
Select switch database :use articledb
insert data :db.comment.insert({bson data })
Query all the data :db.comment.find();
Condition query data :db.comment.find({ Conditions })
Query the first record that meets the criteria :db.comment.findOne({ Conditions })
Query the first few records that meet the criteria :db.comment.find({ Conditions }).limit( Number of pieces )
Query qualified skipped records :db.comment.find({ Conditions }).skip( Number of pieces )
Modifying data :db.comment.update({ Conditions },{ Revised data }) or db.comment.update({ Conditions },{$set:{ To modify the field of the part : data })
Modify the data and add a field value automatically :db.comment.update({ Conditions },{$inc:{ Self increasing field : Step value }})
Delete data :db.comment.remove({ Conditions })
Statistics query :db.comment.count({ Conditions })
Fuzzy query :db.comment.find({ Field name :/ Regular expressions /})
Conditional comparison operations :db.comment.find({ Field name :{$gt: value }})
Contains the query :db.comment.find({ Field name :{$in:[ value 1, value 2]}}) or db.comment.find({ Field name :{$nin:[ value 1, value 2]}})
Conditional join query :db.comment.find({$and:[{ Conditions 1},{ Conditions 2}]}) or db.comment.find({$or:[{ Conditions 1},{ Conditions 2}]})
15. Indexes Index
16. Operation of index
db.collection.getIndexes() Look at the index
db.collection.dropIndex(index) The index can be removed by name , Or specify rules to delete , If not index Means delete all , among _id It is not allowed to delete
give an example :db.comment.dropIndex({userid:1})
16. Use of index
Implementation plan : To check the status of the query , If the query time is based on index query
grammar :db.collection.find(query,options).explain(options)
give an example :
db.comment.find({userid:"1003"}).explain()
Before indexing :
After indexing :
Cover queries :
边栏推荐
- Anxin vb01 offline voice module access intelligent curtain guidance
- B_ QuRT_ User_ Guide(37)
- The 19th Zhejiang Provincial College Programming Contest VP record + supplementary questions
- Idea automatically generates serialVersionUID
- 伸展树(一) - 图文解析与C语言实现
- Open source hardware small project: anxinco esp-c3f control ws2812
- Home appliance industry channel business collaboration system solution: help home appliance enterprises quickly realize the Internet of channels
- Anxin can internally test offline voice module vb-01 to communicate with esp-c3-12f
- One week learning summary of STL Standard Template Library
- [stm32+esp8266 connects to Tencent cloud IOT development platform 3] stm32+esp8266-01s dynamically registers devices on Tencent cloud (at instruction mode) -- with source code
猜你喜欢
postgis学习
Extended tree (I) - graphic analysis and C language implementation
Anxin vb01 offline voice module access intelligent curtain guidance
Given an array, such as [7864, 284, 347, 7732, 8498], now you need to splice the numbers in the array to return the "largest possible number."
Live-Server使用
Anxinco EC series modules are connected to the multi protocol access products of onenet Internet of things open platform
PCB wiring rules of PCI Express interface
Ora-02437 failed to verify the primary key violation
SAP HR social work experience 0023
MySQL Index Optimization Practice II
随机推荐
B_QuRT_User_Guide(39)
HDU 4747 mex "recommended collection"
List. How to achieve ascending and descending sort() 2020.8.6
Ora-02437 failed to verify the primary key violation
Boost regex library source code compilation
redis缓存工具类,值得拥有~
[compilation principle] lexical analysis design and Implementation
SAP HR 劳动合同信息 0016
POJ2392 SpaceElevator [DP]
Spark 离线开发框架设计与实现
MATLAB signal processing [Q & A essays · 2]
系统设计概述
B_ QuRT_ User_ Guide(39)
B_ QuRT_ User_ Guide(38)
【7.5】15. Sum of three numbers
sql 数据库执行问题
KeePass realizes automatic input of web pages
Oracle string sorting
ASP. Net core middleware request processing pipeline
Markdown