当前位置:网站首页>Get started with mongodb

Get started with mongodb

2022-07-07 23:38:00 Clock in the opposite direction 197

Catalog

1. brief introduction

2.  characteristic :

3. Download from the official website

4. start-up

4.1 Start service in command parameter mode

 4.2 Start the service in profile mode

5.shell Command connection

6.Linux Command to install

7.Docker install

8. Basic use of commands

8.1 Operation of database

8.2 Database deletion

8.3 Set operations

9. Document insertion and query

10. Document update

11. Document delete

12. Document paging query

13. More complex queries

14. Summary of common commands

15. Indexes Index

16. Operation of index

 16. Use of index


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.24.1.13;

y An even number indicates that the current version is stable , Such as :1.6.34.0.10;
z Is the revision number , The bigger the number, the better .
Download and unzip :

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

db. Collection name .remove( Conditions )                  Delete the syntax structure of the document
db.comment.remove({})                       Delete all data
db.comment.remove({_id:"1"})                Delete specified row

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 /})

or
db. aggregate .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

MongoDB Index usage B Tree data structure ( Exactly B-Tree,MySQL yes B+Tree
Single field index
Support the creation of user-defined ascending order in a single field of the document / descending index , It is called a single word index , Index and sort a single field , The sort order of the index keys is not important , because MongoDB You can traverse the index in the recognized direction
Composite index
User defined indexes that support multiple fields , Composite index
give an example : If the composite index is from { userid: 1, score: -1 } form , Then the index first presses userid Positive sequence sort , then
At every userid Within the value of , Press... Again score Reverse sort
Other indexes
Geospatial index (Geospatial Index)、 Text index (Text Indexes)、 Hash index (Hashed Indexes).
Geospatial index
In order to support the effective query of geospatial coordinate data ,MongoDB Two special indexes are provided : Two dimensional index of planar geometry is used to return the result and spherical surface is used to return the result
Two dimensional spherical index of Geometry .
Text index
MongoDB Provides a type of text index , Support searching string content in the collection . These text indexes don't store language specific stop words ( for example “the”“a”“or”),
And the words in the set are used as stems , Store only the root word .
Hash index
To support hash based fragmentation ,MongoDB Provides a hash index type , It indexes a hash of field values . These indexes have a more random distribution of values within their ranges , But only
Equal matching , Range based queries are not supported .

16. Operation of index

db.collection.getIndexes()                                          Look at the index


db.collection.createIndex(keys, options)                     Create index keys On that field option Indicates that... Can be selected , such as unique Uniqueness
give an example :db.comment.createIndex({userid:1})                1 Expressing ascending order ,-1 Representation of descending order , If there are multiple fields inside, it means to create a composite 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 :

When the query condition and query projection contain only index fields ,MongoDB Return results directly from the index , Without scanning any documents or bringing them into memory . These overridden queries can
Very effective .

 

     

原网站

版权声明
本文为[Clock in the opposite direction 197]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072057212367.html