当前位置:网站首页>My name is mongodb, don't understand me. After reading my story, you will get started!

My name is mongodb, don't understand me. After reading my story, you will get started!

2020-11-23 00:19:52 osc_ ninety-two million one hundred and eighty-one thousand sev

My name is MongoDb, Don't understand me. After reading my story, you'll get started !

This is a mongo The basic chapter , It will be updated continuously 4 piece

Hello, everyone. My name is MongoDb, since 07 year 10 month 10gen The team brought me into the world , I have already 13 How old are you , Now more and more friends are hugging me , I'm glad . I am a NoSQL A member of the big family , I am a C++ My son . In order to let you know me better , Today, I'd like to introduce myself from the perspective of simple use .

First of all, let's introduce our big family NoSQL Well

NoSQL It's just his abbreviation , His Chinese name is Non relational database , The foreign name is Not Only SQL. It's a complement to relational databases (RDBMS).RDBMS Pursue highly structured data storage and query 、 Strict data consistency ;NOSQL Don't care about the form , Focus on efficiency ,NOSQL It's high performance 、 Modeless 、 Highly scalable distributed database ,NOSQL There are four types of storage : Key value pair storage 、 Column store 、 Document storage 、 Graphic data storage .NoSQL Let's just briefly introduce this , That's not the point today , Now I'd like to focus on my own (MongoDb), ha-ha !

MongoDb Self introduction.

MongoDb Is a key value pair for document storage NOSQL database , Is a non relational database closest to a relational database . Use... On data storage structures and queries BJOSN( Be similar to JSON) structure ,BJOSN Support multi tier institutions , In the specific use process , It's more like manipulation Javascript Script . It is because MongoDb The pattern of nihilism , It becomes more flexible in practical applications , extensible . And RDBMS equally , Support primary key 、 Indexes 、 Retrieval and other operations , Because it is unstructured, it does not support join Inquire about .

MongoDb Basic concepts of

The specific database installation will not be introduced , Search and push online .MongoDb use BJON Storage of documents , So the basic structure concept can be combined with JSON imagine : Field 、 file 、 aggregate 、 database , This sum RDBMS Properties of 、 Column 、 surface 、 Database is one-to-one correspondence . Here's a table to illustrate :

 

RDBMS

MongoDb

Concept

explain

Concept

explain

database

database

database

database

table

surface

collection

aggregate

row

That's ok

document

file : Corresponding one BJSON

column

Column

field

Field :BJSON A specific field in

 

A simple table display is not intuitive enough , Let's take a picture to illustrate it !

User authority management

In the generation environment database management , Database permission is a very important function . In terms of specific authority , It needs to be controlled globally , Access to specific data is required , In the specific authority classification, it includes : read 、 Reading and writing 、 Administrator, etc . The following list describes mongodb Built in permissions for :

Permission to name

Permission specification

read

Allows the user to read the specified database

readWrite

Allows users to read and write to a specified database

dbAdmin

Allows the user to execute administrative functions in the specified database , Like index creation 、 Delete , View statistics or access system.profile

userAdmin

Allow the user to system.users A collection of written , You can find the specified database to create 、 Delete and manage users

clusterAdmin

Only in admin Available in the database , Gives the user administrative rights to all sharding and copy-set related functions .

readAnyDatabase

Only in admin Available in the database , Give the user read rights to all databases

readWriteAnyDatabase

Only in admin Available in the database , Gives the user read and write access to all databases

userAdminAnyDatabase

Only in admin Available in the database , That gives the user all the databases userAdmin jurisdiction

dbAdminAnyDatabase

Only in admin Available in the database , That gives the user all the databases dbAdmin jurisdiction .

root

Only in admin Available in the database . Super account , Super authority

Through the table above , We can figure out : According to the scope of authority , Permissions are divided into two categories : Permissions for each library 、 Permissions for all databases . According to different authority classification , There are also some differences in the assignment format , In the specific user rights allocation , A user can assign multiple permissions at the same time .

When adding a new user, the format of authority initialization is :

Initialize the command format for all database permissions :

db.createUser({user:" user name ",pwd:" password ",roles:[" Permission value "]})

Initializes the command format for the specified database permissions :

db.createUser({user:" user name ",pwd:" password ",roles:[ {role:" Permission value ",db:" Corresponding database "},{role:" Permission value ",db:" Corresponding database "}….]})

That may not be easy to understand , Well, let's use the actual work as an example .

Conditional assumption : Yes 3 A database :testdb001、testdb002

Users need to be assigned the corresponding permissions

user

The permissions that need to be assigned

Specific orders

adminRoot

Super account , Have all operation rights of all databases

use admin

db.createUser({user:"adminRoot",pwd:"123",roles:["root"]})

adminWrite

Super write account , Have read and write permissions for all databases

use admin

db.createUser({user:"adminWrite",pwd:"123",roles:["readWriteAnyDatabase"]})

adminRead

Super write account , Have read access to all databases

use admin

db.createUser({user:"adminRead",pwd:"123",roles:["readAnyDatabase"]})

001Write

Have a database testdb001 Read and write permissions for

use admin

db.createUser({user:"001Write",pwd:"123",roles:[ {role:"readWrite",db:" testdb001"}]})

001Read

Have a database testdb001 Read operation permission of

use admin

db.createUser({user:"001Read",pwd:"123",roles:[ {role:"read",db:" testdb001"}]})

012Write

Have a database testdb001、testdb002 Read and write permissions for

use admin

db.createUser({user:"001Write",pwd:"123",roles:[ {role:"readWrite",db:" testdb001"},{role:"readWrite",db:" testdb002"}]})

Through practical examples , You should have an understanding of the new initialization operation command of permissions , Well, next, we'll talk about the permission according to the new operation command , In fact, the specific permission format of root system and initialization is one to , As follows :

Update command format for all database permissions :

db.updateUser(" Updated user name ",{pwd:" The updated password ",roles:[" Permission value "]})

Update command format for specified database permissions :

db.updateUser(" Updated user name ",{pwd:" The updated password ",roles:[{role:" Permission value ",db:" Corresponding database "},{role:" Permission value ",db:" Corresponding database "}….]})

Be careful :updateUser The second parameter of has two nodes :pwd and roles. If you don't need to update the data of a node , Then you can simply not use this node .

example : Continue with the example above

User update statement

Specific orders

Update user adminRoot The password for 111111

use admin

db.updateUser("adminRoot",{pwd:"111111"})

to update 001Write At the same time, it has testdb001 and testdb002 Write permission of

use admin

db.updateUser("adminWrite",{roles:[ {role:"readWrite",db:" testdb001"},{role:"readWrite",db:" testdb002"}]})

to update 001Read At the same time, it has testdb001 and testdb002 Read permission of , And the password is updated to 111111

use admin

db.updateUser("001Read",{ pwd:"111111",roles:[ {role:"read",db:" testdb001"},{role:"read",db:" testdb002"}]})

 

database (database)

Specific database concepts and RDBMS Agreement , One mongodb You can create multiple databases , Different databases can also be stored in different mongodb. The default database of the system includes :admin( Storage user rights related )、config( Configuration information )、local( Log information ). Our common operations for databases include : establish 、 Delete . The specific implementation is as follows :

establish :use Database name

When the database name does not exist , The system automatically creates ( Cannot display after creation , You need to insert data into it to display ), Switch when there is one .

Delete : First switch to the database for , And then in the dropDatabase command

use The name of the deleted database

db.dropDatabase()

 

aggregate (Collection)

A set is mongodb A grouping of data stores in , And a table in a relational database is a corresponding relationship . There is no fixed format for the document data stored in the collection , You can freely store different formats of bjson data , But in practice , We still store the same type of bjson data . The common operation commands for a collection are as follows :

Create set :

db.createCollection( Collection name , Set rule ), The second parameter is a json data , Not required , The specific parameter node is :

Set rule :{ capped : optional bool type : Set whether the change set is a fixed set ,

true: For a fixed set , The data in the set cannot be modified , And size Pairs using , Represents when the collection reaches the specified size , The historical data will be automatically covered ( The first data to add ),

size: Fill in the number type : Specifies the maximum storage data for the collection ( Number of bytes ), When the collection reaches the specified size , The historical data will be automatically covered ( The first data to add ) }

max: Fill in the number type : Specifies the maximum number of documents stored in the collection , When the number of documents is greater than max When the value of , Will automatically replace historical documents

}

collection Delete :

db. Collection name .drop();

 

file (Document)

A document is just a set of key values (key-value) Data pair ( One BJON), A specific document structure can be nested in multiple layers , The data structure between different documents can be different , And the data types of the same node can be different , This is the RDBMS The biggest difference is , It also established MongoDB High scalability . In fact, it is one by one jon Formatted data .

Document common operation command summary :

operation

Command format

insert data

db. Collection name .insert(json object )  json It can be a single piece of data , It can also be a collection list

Update data

db. Collection name .update(query , update,option)

query : Updated document conditions json

update: The updated document json

option: Update the way json, The parameter format is { upsert: boolean, multi : boolean }

upsert: Not a required parameter , If it does not exist, whether to add , The duty of true when , If there is no eligible data , Just insert the data , , The default is false

multi: Not a required parameter , Whether to update all data that meet the requirements , The duty of true when , All eligible data are updated , The default is false

Delete data

db. Collection name .remove(query , justOne )

query :( Optional ) Conditions for deleted documents .

justOne : ( Optional ) If it is set to true or 1, Only one document is deleted , If this parameter is not set , Or use default values false, Deletes all documents that match the criteria .

Query data

db. Collection name .find(jison Object query criteria )

 

Field

Fields are easy to understand , It's in the document json Every node of the data .

Through to mongodb A brief introduction to the operation of , In fact, it is not difficult to find the following characteristics :

1. Whether it's an addition to the document 、 Delete 、 Change 、 Check the parameters of the operation. Everything is json, In practice , according to json It can be operated by means of .

2. Databases and collections can be created automatically in use :

2.1 use When switching databases , If no database is created automatically ;

2.2 db. aggregate .insert() When the set doesn't exist , The system automatically creates a collection .

Mongodb These features are not very cool to use . Now from the creation of the database , To document the overall operation process, write some demo examples , To impress .

operation

Command format

Connect to mongdb

mongo

use admin

db.auth(" user name "," User password ")

Create database bd001 And table user001

use bd001

db.createCollection("user001")

Create database bd002 and user002

use bd002

db.createCollection("user002")

View all databases

show dbs

Output results

admin   0.000GB

config  0.000GB

local   0.000GB

bd001  0.000GB

bd002  0.000GB

Delete the collection user002

use db002

db.user002.drop()

Delete database db002

use db002

db. dropDatabase()

To watch user001 Insert a piece of data

use db001

db.user001.insert({name:” Programmer training tour ”,age:2})

To watch user001 Insert two pieces of data

use db001

db.user001.insert([

{name:"mongodb",age:12,type:"database"},

{"name":".net",from:"U.S.A"}

])

To watch user001 Insert three pieces of data

use db001

db.user001.insert([

{name:"zhangsan",age:12,sex:"man"},

{name:"zhangsan",age:18,sex:"woman"},

{name:"zhangsan",age:22,sex:"man"}

])

Look up the data in the table

use db001

db.user001.find()

Query results :

{ "_id" : ObjectId("5fa0ab4195368a0bf20f38cd"), "name" : " Programmer training tour ", "age" : 2 }

{ "_id" : ObjectId("5fa0abb495368a0bf20f38d0"), "name" : ".net", "from" : "U.S.A" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d1"), "name" : "zhangsan", "age" : 12, "sex" : "man" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d2"), "name" : "zhangsan", "age" : 18, "sex" : "woman" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d3"), "name" : "zhangsan", "age" : 22, "sex" : "man" }

In the query table name=" Programmer training tour " The data of

use db001

db.user001.find({name: " Programmer training tour "})

Query results :

{ "_id" : ObjectId("5fa0ab4195368a0bf20f38cd"), "name" : " Programmer training tour ", "age" : 2 }

Modify the table name=" Programmer training tour " Data. age=66, And add a node from node

use db001

db.user001.update({name: " Programmer training tour "},{$set:{age:66,from: "CDU"}})

View the modified data

use db001

db.user001.find({name: " Programmer training tour "})

Query results :

{ "_id" : ObjectId("5fa0ab4195368a0bf20f38cd"), "name" : " Programmer training tour ", "age" : 66,from: "CDU"}

The data is already the modified data

Modify the table name=" zhangsan" Data. age=88, And only modify one piece of data that meets the requirements

use db001

db.user001.update({name: "zhangsan"},{$set:{age:88}},{ multi:false})

see name=" zhangsan" Revised data , Whether there is only one piece of data age Changed to 88?

use db001

db.user001.find({name: "zhangsan"})

Query results :

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d1"), "name" : "zhangsan", "age" : 88, "sex" : "man" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d2"), "name" : "zhangsan", "age" : 18, "sex" : "woman" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d3"), "name" : "zhangsan", "age" : 22, "sex" : "man" }

Only the first one age Was modified to 88

Modify the table name=" zhangsan" Data. age=99, Modify all data that meets the requirements

use db001

db.user001.update({name: "zhangsan"},{$set:{age:99}},{ multi:true})

see name=" zhangsan" Revised data , Is it only for all data age Changed to 99?

use db001

db.user001.find({name: "zhangsan"})

Query results :

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d1"), "name" : "zhangsan", "age" : 99, "sex" : "man" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d2"), "name" : "zhangsan", "age" : 99, "sex" : "woman" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d3"), "name" : "zhangsan", "age" : 99, "sex" : "man" }

name="zhangsan" All data for age Was modified to 99

modify name="lisi" Of age=77

use db001

db.user001.update({name: "lisi"},{$set:{age:77}})

View data modification results

Because there is no name=lisi The data of , No data can be found

use db001

db.user001.find({name: "lisi"})

Query results :

No data

modify name="lisi" Of age=77, If not, add

use db001

db.user001.update({name: "lisi"},{$set:{age:77}},{ upsert:true})

View data modification results

A new one has been added name="lisi" The data of

use db001

db.user001.find({name: "lisi"})

Query results :

{ "_id" : ObjectId("5fa0b3731b875939723ffe26"), "name" : "lisi", "age" : 77 }

Delete one name="zhangsan" The data of

use db001

db.user001.rmove({name: "zhangsan"},1)

View delete results

use db001

db.user001.find({name:"zhangsan"})

Query results :

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d2"), "name" : "zhangsan", "age" : 18, "sex" : "woman" }

{ "_id" : ObjectId("5fa0ad3b95368a0bf20f38d3"), "name" : "zhangsan", "age" : 22, "sex" : "man" }

name="zhangsan" Data from the original 3 The bar becomes 2 strip , It's been deleted

Delete all name="zhangsan" The data of

use db001

db.user001.rmove({name: "zhangsan"})

View delete results

use db001

db.user001.find({name:"zhangsan"})

Query results :

No data

name="zhangsan" All of the data has been deleted

Through the above practical operation , We found that all new documents automatically generate a node ”_id” ObjectId), The _id yes mongodb The system automatically generates It's like a unique primary key , It can be quickly generated and sorted , contain 12 bytes, The meaning is :

1. front 4 Four bytes means create  unix  Time stamp , GMT  UTC  Time , It's later than Beijing time 8 Hours

2. Next 3 Bytes is the machine identity code

3. The two bytes immediately followed by the process id form PID

4. The last three bytes are random Numbers

//inotgo.com/imagesLocal/202011/23/20201123001614104o_5.jpg

Of course _id You can also customize the assignment according to your actual needs .

Well, let's write about it today , Through this article to the mongo Have a preliminary understanding of , Next article , Let's have a detailed inquiry together ,mongo There's still a lot to talk about . Thank you for checking .

END
Originality is not easy. , Thanks for scanning support , Get more , thank you :

版权声明
本文为[osc_ ninety-two million one hundred and eighty-one thousand sev]所创,转载请带上原文链接,感谢

随机推荐