MongoDB is a representative of non-relational database, a high-performance database based on key and value storage. Often stored as a crawler database.

MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable, high-performance data storage solutions for WEB applications.

MongoDB is a product between a relational database and a non-relational database. The non-relational database has the most abundant functions and is the most similar to a relational database.

The connectionMongoDB

Format: mongo: / / username: password @ host: port/database

  • mongodb://: Fixed connector, must be specified.
  • username:password: Indicates the user name and password. If the password is blank, this parameter is optional
  • host: specifyhost.URIIs the onlymandatoryItems. It specifies the address of the server to connect to.
  • port: Specifies the port. If this parameter is not specified, the default value is27017
  • database: If this parameter is not specified, it is enabled by defaulttestThe database.

createThe database,A collection of

Trying to create a databaseUnderground station

We named our first database in Chinese

>Use underground traffic stationSwitched to DB underground traffic station> dbUnderground stationCopy the code

If the database already exists, it is switched to this library, if not, it is created.

Viewing the database list

> show dbsAdmin 0.000GB Config 0.000GB Local 0.000GBCopy the code

In MongoDB, the database must have data in order to see it in the list, which is very different from other databases, and we will try to insert data later.

Try to create a collectionQuotations

> db.createCollection("Quotations")
{ "ok" : 1 }
Copy the code

A collection is created.

View all collections in the database underground traffic station

> show collections
Quotations
Copy the code

Delete library is more simple, run road is difficult!!

Deleting a database

>Use underground traffic stationSwitched to DB underground traffic station
> db.dropDatabase()
{ "dropped" : "地下交通站", "ok" : 1 }
Copy the code

Such a MongoDB database is gone.

Deleting a collection

>Use underground traffic stationSwitched to DB underground traffic station> db.Quotations.drop()  # Delete collection
Copy the code

So the Quotations collection in the underground transportation station will be gone!

Inserted into the document

MongoDB is a document-oriented database, which is relatively simple and easy to operate.

A piece of data in MongoDB is considered a document, and a table is called a Collection.

Db.collection.insertone () is used to insert a new document (a single JSON object) into the collection

Db.collection.insertmany () is used to insert multiple documents (a list of JSON objects) into a collection

Attempt to insert a piece of data

Insert a data entry into the Quotations set in the underground transportation station database

>Use underground traffic stationSwitched to DB underground traffic station
> db.Quotations.insert({Name: 'I owe you enough money to eat here for two years ', createDate: '2021-04-15'}) WriteResult({"nInserted" : 1})Copy the code

View inserted document records

> db.Quotations.find({}){"_id" : ObjectId("6078e9743252cc07e092d204"), "name" : "Jia GUI ", "description" :" Lao Lao here owe enough money to eat for two years ", "createDate" : "2021-04-15"}Copy the code

You can see that the MongoDB collection automatically generates the _ID field for our unique index!!

Attempted to insert multiple pieces of data

> db.Quotations.insertMany([{name: 'The weight is cooked ',createDate: '2021-04-15'}, {name:' Jia GUI ',description: 'The weight is cooked ',createDate: '2021-04-15'}, {name:' Jia GUI ',description: 'I covered my head, my face and my butt and I started to fight with him ',createDate: '2021-04-16'}, {name:' Black vine ',description: 'Who do you call me? I'm black vine ',createDate: }, {name: 'Sun Youfu ',description:' no fish without water, no donkey without you ',createDate: '2021-04-17'}])Copy the code
> db.Quotations.find({}){"_id" : ObjectId("6078e9743252cc07e092d204"), "name" : "Jia GUI ", "description" :" Lao Lao here owe enough money to eat for two years ", "createDate" : "2021-04-15"} {"_id" : ObjectId(" 6078ebd395708b77ad7a8Bd8 "), "name" : } {"_id" : ObjectId(" 6078ebd395708b77ad7a8Bd9 "), "name" : ", "description" : "I covered my head, covered my face and pout my butt and started to fight with him ", "createDate" : "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : "Black vine ", "description" :" Who do you think I am? I am black vine ", "createDate" : "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bdb"), "name" : "Sun Youf ", "description" : "No fish without water, no donkey without you ", "createDate" : "2021-04-17"}Copy the code

Update the document

Try to updatenameField (single document)

> db.Quotations.update({'name':'black cane'}, {$set:{name: 'black cane',description: 'All traitors are stupid',createDate: '2021-04-16'}})
Copy the code

Changes to take effect

> db.Quotations.find({})                                                                                 1-04-16'}}){"_id" : ObjectId("6078e9743252cc07e092d204"), "name" : "Jia GUI ", "description" :" Lao Lao here owe enough money to eat for two years ", "createDate" : "2021-04-15"} {"_id" : ObjectId(" 6078ebd395708b77ad7a8Bd8 "), "name" : } {"_id" : ObjectId(" 6078ebd395708b77ad7a8Bd9 "), "name" : ", "description" : "I covered my head, covered my face and pout my butt and started to fight with him ", "createDate" : "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : "blackrattan ", "description" : "createDate" : "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bdb"), "name" : "Sun Youfu ", "description" :" no fish without water, no donkey without you ", "createDate" : "2021-04-17"}Copy the code

Try to update all documents

> db.Quotations.update({'name':'Gu Gui'}, {$set: {name: 'Gu Gui',description: 'I don't know! I know she looks big. Hey! ',createDate: '2021-04-16'}},{multi:true})
Copy the code
> db.Quotations.find({}){"_id" : ObjectId("6078e9743252cc07e092d204"), "name" : "Jia GUI ", "description" :" I don't know! I know she looks like hey!" , "createDate" : "2021-04-16"} {"_id" : ObjectId(" 6078ebd395708b77AD7a8Bd8 "), "name" : "description" : } {"_id" : ObjectId(" 6078ebd395708b77ad7a8Bd9 "), "name" : "I don't know! I know she looks like hey!" , "createDate" : "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : "Description" : } {" id" : ObjectId("6078ebd395708b77ad7a8bdb"), "name" : "Sun Youfu ", "description" :" no water, no fish, no you, no donkey ", "createDate" : "2021-04-17"}Copy the code

Here we set the multi parameter to True, meaning that all documents matching the query criteria will be updated

I found that all the quotations named Jia GUI had been changed

If no, add it

Set the upsert parameter to True. If the update does not exist, a new one is added.

> db.Quotations.update({'name':'wrasse sichuan'}, {$set: {'name' : 'wrasse sichuan'.'description' : 'Go to The East pass and make trouble.'}},{upsert:true})
Copy the code
> db.Quotations.find({}){"_id" : ObjectId("6078e9743252cc07e092d204"), "name" : "Jia GUI ", "description" :" I don't know! I know she looks like hey!" , "createDate" : "2021-04-16"} {"_id" : ObjectId(" 6078ebd395708b77AD7a8Bd8 "), "name" : "description" : } {"_id" : ObjectId(" 6078ebd395708b77ad7a8Bd9 "), "name" : "I don't know! I know she looks like hey!" , "createDate" : "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : "Description" : } {" id" : ObjectId("6078ebd395708b77ad7a8bdb"), "name" : "CreateDate" : "2021-04-17", "createDate" : "2021-04-17"} {" id" : ObjectId("6078ee01249a48b5bb83b936"), "name" : "Setokawa ", "description" :" To dongguan, disturbance work "}Copy the code

A new document with the name Seagawa has been added

In the meantime, I recommend using the update_One method to update a single document and the update_many method to update multiple documents

Delete the document

Delete all documents that match the query criteria

> db.Quotations.remove({'name':'Gu Gui'})
WriteResult({ "nRemoved" : 2 })
Copy the code
> db.Quotations.find({}){"_id" : ObjectId(" 6078ebd395708b77ad7a8Bd8 "), "name" : "Gold mark ", "description" :" This weight is also TM stew ", "createDate" : } {"_id" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : ObjectId("6078ebd395708b77ad7a8bda"), "description" : "createDate" : "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bdb"), "name" : "Sun Youf ", "description" : } {" id" : ObjectId(" 6078EE01249a48b5bb83b936 "), "name" : "Seto ", "description" :" to dongguan, trouble work "}Copy the code

That would have wiped out any documentation with the name Of Jia GUI

Deletes all documents in the collection

> db.Quotations.remove({})
Copy the code

{} indicates unconditional. By default, all documents are removed, which is equivalent to deleting the collection.

Query the document

MongoDB general syntax for querying data

db.collection.find(query, projection)

Conditions of the query

Specify a non-_ID field

>Use underground traffic stationSwitched to DB underground traffic station> db.Quotations.find({},{'_id': 0}){"createDate" : "2021-04-16"} {"name" : "sunyoufu ", "description" : "No water, no fish, without you there is no donkey", "createDate" : "2021-04-17"} {" name ":" wrasse sichuan ", "description" : "go to dongguan, mischievous work"} {" name ": "Gold mark ", "createDate" : "2021-04-26", "description" :" Adjutant Liu, you remember, let the imperial army pee first." } {"name" : "createDate" : "2021-04-18", "description" : "I spat dog shit in his face"} {"name" : "gold mark ", "createDate" : "2021-04-18", "description" :" I spat dog shit in his face "} {"name" : "gold mark ", "createDate" : "2021-04-26", "Description" : "Adjutant Liu, you remember, let the imperial army pee first." }Copy the code

To beautify the output, you can use the pretty() method, which makes no sense for SQL transactions

db.Quotations.find({},{'_id':0}).pretty()
Copy the code

ANDThe query

Select * from ‘createDate’ where name = ‘gold’ and createDate = ‘2021-04-26’

> db.Quotations.find({"name":"Gold standard"."createDate":"2021-04-26"}){"_id" : ObjectId(" 6078F0e31E12A856CF9525da "), "name" : "gold ", "createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." } {" id" : ObjectId(" 6078f2091e12A856CF9525DD "), "name" : ObjectId(" createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." }Copy the code

ORThe query

Select * from ‘name’ where name is’ jia GUI ‘or’ description is’ where name is’ jia GUI ‘

> db.Quotations.find({$or: [{"name":"Gu Gui"}, {"description": "All traitors are stupid."}]}){"_id" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : ObjectId(" name" : ObjectId), "description" : "createDate" : ObjectId(" name" : ObjectId) } {" id" : ObjectId(" 6078f2091e12A856CF9525DC "), "name" : "createDate" : "2021-04-18", "description" : "I spit shit in his face"}Copy the code

As you can see, the OR query uses an explicit operation ($OR followed by a list of conditions). The OR operation must be explicit; there is no implicit OR operation.

The AND query operation above can also be written explicitly

> db.Quotations.find({$and: [{"name":"Gold standard"}, {"createDate": "2021-04-26"}]}){"_id" : ObjectId(" 6078F0e31E12A856CF9525da "), "name" : "gold ", "createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." } {" id" : ObjectId(" 6078f2091e12A856CF9525DD "), "name" : ObjectId(" createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." }Copy the code

Discovery is ok!!

ANDORA combination of

Select * from [createDate = 2021-04-18] where name = [createDate = 2021-04-18] where name = [createDate = 2021-04-18] where name = [createDate = 2021-04-18

The pseudo-SQL statement is expressed as:

Where createDate='2021-04-18' AND (name =' jiagui 'OR description =' jiagui ')

> db.Quotations.find({"createDate": "2021-04-18".$or: [{"name": "Gu Gui"}, {"description": "All traitors are stupid."}]}){"_id" : ObjectId(" 6078f2091e12a856CF9525DC "), "name" : "Jia Jia ", "createDate" : "2021-04-18", "description" :" I puck in his face "}Copy the code

Advanced query

Range query and regular query

  • $ltLess than
  • $gtIs greater than
  • $lteLess than or equal to
  • $gteGreater than or equal to
  • $neIs not equal to
  • $inWithin the scope of
  • $ninOut of range

Example Query all documents created at a time greater than 2021-04-17

> db.Quotations.find({"createDate" : {$gt : "2021-04-17"}}){"_id" : ObjectId(" 6078F0e31E12A856CF9525da "), "name" : "gold ", "createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." } {" id" : ObjectId(" 6078f2091e12A856CF9525DC "), "name" : "jiagai ", "createDate" : "2021-04-18", "description" : } {" id" : ObjectId(" 6078f2091e12a856CF9525dd "), "name" : "createDate" : "2021-04-26", "Description" : "Adjutant Liu, you remember, let the imperial army pee first." }Copy the code

Select * from ‘createDate’ where ‘createDate’ = ‘2021-04-26’ and ‘name’ = ‘gold’

> db.Quotations.find({"name" : {$ne : "Gold standard"},"createDate": {$lt : "2021-04-26"}}){"_id" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : ObjectId("6078ebd395708b77ad7a8bda"), "name" : ObjectId(" name" : ObjectId), "description" : "createDate" : ObjectId(" name" : ObjectId) "2021-04-16"} {"_id" : ObjectId("6078ebd395708b77ad7a8bdb"), "name" : "Sun Youf ", "description" : } {" id" : ObjectId(" 6078f2091e12a856CF9525dc "), "name" : "Jia GUI ", "createDate" : "2021-04-18", "description" :" I spit shit in his face "}Copy the code

Select * from where [createDate > 2021-04-02] where [createDate > 2021-04-02]

> db.Quotations.find({"name" : {$in : ["Gold standard"."Gu Gui"]},"createDate": {$gt : "2021-04-02"}}){"_id" : ObjectId(" 6078F0e31E12A856CF9525da "), "name" : "gold ", "createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." } {" id" : ObjectId(" 6078f2091e12A856CF9525DC "), "name" : "jiagai ", "createDate" : "2021-04-18", "description" : } {" id" : ObjectId(" 6078f2091e12a856CF9525dd "), "name" : "createDate" : "2021-04-26", "Description" : "Adjutant Liu, you remember, let the imperial army pee first." }Copy the code
  • $regexMatches a regular
  • $existsWhether the attribute exists
  • $typeType judgment
  • $modDigital mode operation
  • $textText query
  • $whereAdvanced Search

Use the regular statement to match all documents with gold in name

> db.Quotations.find({"name": {"$regex":"Jinbiao"}}){"_id" : ObjectId(" 6078F0e31E12A856CF9525da "), "name" : "gold ", "createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." } {" id" : ObjectId(" 6078f2091e12A856CF9525DD "), "name" : ObjectId(" createDate" : "2021-04-26", "description" : "Adjutant Liu you remember, let the imperial army first urine." }Copy the code

Matches all documents that start with my description using a regular statement

> db.Quotations.find({"description": {"$regex":"^ me"}}){"_id" : ObjectId(" 6078f2091e12a856CF9525DC "), "name" : "Jia Jia ", "createDate" : "2021-04-18", "description" :" I puck in his face "}Copy the code

Match any document that begins with me and ends with description using a regular statement

> db.Quotations.find({"description": {"$regex":"^ me.* shit $"}}){"_id" : ObjectId(" 6078f2091e12a856CF9525DC "), "name" : "Jia Jia ", "createDate" : "2021-04-18", "description" :" I puck in his face "}Copy the code

For more advanced query usage, please refer to the MongoDB documentation

Aggregation function

The sorting

The sort() method is used to sort data in MongoDB. The sort() method can specify the fields to be sorted by parameters and use 1 and -1 to specify the sorting mode, where 1 is ascending and -1 is descending.

We always like to use the time dimension to sort the documents in the collection

> db.Quotations.find({},{"_id":0}).sort({"createDate"1}) : -{"name" : "gold mark ", "createDate" : "2021-04-26", "description" :" } {"name" : "gold mark ", "createDate" : "2021-04-26", "description" :" } {"name" : "createDate" : "2021-04-18", "description" : "I spat dog shit in his face"} {"name" : "sun Youfu ", "description" : "No water, no fish, no donkey ", "createDate" : "2021-04-17", "createDate" : "2021-04-17", "createDate" : "name" :" black rattan ", "description" : "the traitor is as stupid as ", "createDate" : "2021-04-16"} {"name" : "Setokawa ", "description" :" go to Dongguan "}Copy the code

grouping

db.Quotations.aggregate({$group:{_id:{name:"$name"}}})
Copy the code

Group by name and description fields

db.Quotations.aggregate({
    $group:{
        _id:{name:"$name",description:"$description"}
}})
Copy the code

Because there are no computable values in the fields of our existing collection documents

We tried to add a collection field and set it to null

db.Quotations.update({},{$set:{"forceValue": ""}},{multi:true})
Copy the code

Adding random values

Db. Quotations. Update ({" name ":" black cane "}, {$set: {" forceValue ": Math. The random () * 100}}, {multi: true}) db. Quotations. Update ({" name ":" Sun Youfu "}, {$set: {" forceValue ": Math. The random () * 100}}, {multi: true}) db. Quotations. Update ({" name ":" wrasse sichuan "}, {$set: {" forceValue ": Math. The random () * 100}}, {multi: true}) db. Quotations. Update ({" name ":" gold "}, {$set: {" forceValue ": Math. The random () * 100}}, {multi: true}) db. Quotations. Update ({" name ":" Gu Gui "}, {$set: {" forceValue ": Math.random()*100}},{multi:true})Copy the code

The results are as follows

{"name" : "name", "description" : "createDate" : "2021-04-16", "forceValue" : 14.796604243632927} "CreateDate" : "2021-04-17", "forceValue" : 43.71427504449847} {"name" : {"name" : "gold mark ", "createDate" : "name" :" gold mark ", "createDate" : "2021-04-26", "Description" : "Adjutant Liu, you remember, let the imperial army pee first." , "forceValue" : 21.887495918176125} {"name" : "createDate" : "2021-04-18", "description" : "I spat shit in his face ", "forceValue" : 94.18697675337746}Copy the code

Because of the grouping, we need to add several more pieces of document data

Db.Quotations. InsertMany ([{name: "Gold mark",description: "I huang someone to keep the peace",forceValue: math.random ()*100,createDate: {evalue: math.random ()*100,createDate: {evalue: math.random ()*100,createDate: {evalue: math.random ()*100,createDate: {evalue: math.random ()*100,createDate: '2021-04-14'}, {name: 'Blacktop ',description:' There is no other face like yours in all of Asia ',forceValue: math.random ()*100,createDate: '2021-04-22'}, {name: '2021-04-22',description: 'I don't know, I just know ',forceValue: math.random ()*100, createDate: '2021-04-19'}])Copy the code

Groups use aggregate functions

Common aggregate function

  • $sum
  • $avg
  • $max
  • $min
  • $first
  • $last

Group by name and sum using the $sum function to get the following result

  • $matchQuery conditions
  • $groupGroup by field (can be multiple fields) + aggregate functions
> db.Quotations.aggregate(. {"$match":{"createDate":{"$gt":"2021-04-07"}}}, ... {"$group":{"_id":"$name",'forceValue':{"$sum":"$forceValue"}}}, ... ) {"_id" : "jiagui ", "forceValue" : 204.22774268609504} {"_id" :" jiagui ", "forceValue" : 204.22774268609504} {"_id" : "jiagui ", "forceValue" : 204.22774268609504} {"_id" :" jiagui ", "forceValue" : 121.14812944012357} {"_id" : } {"_id" : "sun Youfu ", "forceValue" : 43.71427504449847}Copy the code

This is equivalent to executing in Mysql

select id,sum(forceValue) from Quotations where createDate > "2021-04-07" group by name;  
Copy the code

An average of $avg

> db.Quotations.aggregate(. {"$match":{"createDate":{"$gt":"2021-04-07"}}}, ... {"$group":{"_id":"$name",'forceValue':{"$avg":"$forceValue"}}}, ... ) {"_id" : "jiagui ", "forceValue" : 68.07591422869835} {"_id" :" jiagui ", "forceValue" : 68.07591422869835} {"_id" : "jiagui ", "forceValue" : 68.07591422869835} {"_id" :" jiagui ", "forceValue" : 60.574064720061784} {"_id" : {"_id" : "sun Youfu ", "forceValue" : 43.71427504449847}Copy the code

Multi-field grouping

Sum by createDate + name

> db.Quotations.aggregate(. . {"$match":{"createDate":{"$gt":"2021-04-07"}}}, ... . {"$group":{"_id":{"createDate":"$createDate","name":"$name"},'forceValue':{"$sum":"$forceValue"}}}, ... ...). {"_id" : {"createDate" : "2021-04-11", "name" : "gold"}, "forceValue" : 99.26063352194744} {"_id" : {"createDate" : "2021-04-11", "name" : "gold"}, "forceValue" : 99.26063352194744} {" createDate ", "2021-04-16", "name" : "black cane"}, "forceValue" : 14.796604243632927} {" _id ": {" createDate" : "2021-04-17", "name" : "Sun Youfu"}, "forceValue" : 43.71427504449847} {" _id ": {" createDate" : "2021-04-18", "name" : {" id" : {"createDate" : "2021-04-26", "name" : "gold"}, "forceValue" : 94.18697675337746}, "id" : {"createDate" : "2021-04-26", "name" :" gold "}, 21.887495918176125} {"_id" : {"createDate" : "2021-04-14", "name" : "name"}, "forceValue" : {" id" : {"createDate" : "2021-04-22", "name" : "name"}, "forceValue" : {" id" : {"createDate" : "2021-04-19", "name" : "jiagui"}, "forceValue" : 28.04757175413979}Copy the code

:tada: :tada: :tada: :tada: :tada: :tada: :tada: :tada: :tada: :tada: :tada: :tada: :tada: :tada:

I can’t go any further, so this is the basic introduction to MongoDB :beer:

See the MongoDB documentation for more tutorials