The introduction
The tutorials are based on pony techniques and are suitable for beginners:
- Video: www.youtube.com/watch?v=kmO…
- Warehouse: gitee.com/komavideo/L…
This article is used for mongodb learning note collation
- Complete brain figure: share.mubu.com/doc/7jeYw7a…
- Personal warehouse: github.com/sanhuamao1/… (Includes some operation examples)
- Mongo shell method document: docs.mongodb.com/manual/refe…
- Nodejs driven approach document: docs.mongodb.com/drivers/nod…
What is MongoDB
MongoDB is a NoSql free database, mostly used for data collection and distributed processing (Map/Reduce), especially good at big data processing.
- Database
- Collection — equivalent to a Table
- Document — equivalent to Record
- Official website: www.mongodb.com/
- Database engine ranking: db-engines.com/en/ranking
- Preparation: JavaScript basics
Two mongo installation
- The installation address: www.mongodb.com/try/downloa…
- Video tutorial: www.bilibili.com/video/BV1x5…
3 Basic Commands
Mongo // Enter the mongo command toolhelpUse [db_name] // Create or switch db.stats() // Check the database status db.dropDatabase() // Delete the databaseexit// Exit the mongo command toolCopy the code
Collections of operations
Db.createcollection (<col_name>) // createCollection show collections // display collection db.[col_name].find() // switch collection and view the document Db.[col_name1].renamecollection (<col_name2>) // Rename db.[col_name].drop() // drop the collectionCopy the code
Operation Document (Document)
Db.[col_name]. Insert ({}) // Insert data (being discarded) db.[col_name]. InsertOne ({}) // Insert single data db Db.[col_name].find() // select * from db.[col_name].count();"Monster Hunter World Review"."rank": 2."tag":"game"});
Copy the code
4 Reading documents
Find- Queries documents
To compare
Db. Col. Find ({< key1 > : < value >}) / / equal to the col. Find ({< key > : {$lt: < value >}}) / / less than the col. Find ({< key > : {$lteDb.col.find ({<key>:{);$gt: < value >}}) / / than the col. Find ({< key > : {$gteDb.col.find ({<key>:{);$ne<value>}})// does not equal > db.posts.find({<value>}})"tag": "game"});
> db.posts.find({"rank": {$lt: 4}});
Copy the code
other
Db. Col. Find ({< key1 > : < value >, < key2 > : < value >}) / / and the col. Find ({$or: [{< key1 > : < value >}, {< key2 > : < value >}]}) / / or db. Col. Find ({< key > : {< key > : < expression >}}) / / regular expression the col. Find ({< key > : {$in: [< value1 >, < value2 >]}}) / / within a certain range the col. Find ({< key > : {$exists: true}}) // Db.col.find ({<key>:{$type: <typeDb.posts.find ({db.posts.find() {db.posts.find() {db.posts.find();"title": /u/});
> db.posts.find({"title": /u/, "rank": {$gte:5} });
> db.posts.find({$or: [{"title": /u/}, {"rank": {$gte:4}}]});
> db.posts.find({"rank": {$in: [3,4]} });
> db.posts.find({"istop": {$exists: true}}); > db.orders.find({ name:"Lemony Snicket",
date: {
$gte: new Date(new Date().setHours(00, 00, 00)),
$lt: new Date(new Date().setHours(23, 59, 59)),
},
});
Copy the code
extracting
db.col.find({}, {<key1>: true, <key2>: 1,<key3>:0}) //每条文档只选key1和key2显示,且不显示key3
db.col.findOne(<query>)//只取第一条
db.col.distinct(<key>) //取指定字段所包含的属性值(数组)
> db.posts.find({}, {title:true, rank:1});
> db.posts.find({}, {title:true, rank:1, _id:0});
Copy the code
methods
db.col.find().sort({<key>:<type>}); // In ascending or descending order by key,typeIt can be 1 and -1 db.col.find().limit(<num>); / / article limit according to the number of db. Col. The find (). Skip (< num >) / / skip the article specified number > db. The posts. The find ({}, {_id: 0}), sort ({rank: 1}); > db.posts.find({}, {_id:0}).limit(3);
> db.posts.find({}, {_id:0}).skip(3).limit(3); / / pagingCopy the code
Aggregate – polymerization
Preface – Pipelines
The aggregate pipeline for MongoDB is to pass the MongoDB document to the next pipeline after it has been processed in one pipeline.
- $project: Modifies the structure of the input document. It can be used to rename, add, or delete domains, create computed results, and nest documents.
- Match: Filters data and outputs only the documents that meet the conditions. Match: Filters data and outputs only the documents that meet the conditions. Match: Filters data and outputs only the documents that meet the conditions. Match uses MongoDB’s standard query operations.
- $limit: Limits the number of documents returned by the MongoDB aggregation pipeline.
- $skip: Skips a specified number of documents in the aggregation pipe and returns the remaining documents.
- $unwind: Unwinds an array type field in a document into multiple pieces, each containing a value from the array.
- $group: Groups documents in a collection that can be used for statistical results.
- $sort: Outputs by sorting the input documents.
- $geoNear: Outputs an ordered document close to a geographic location.
> db.article.aggregate(
{ $project: { _id : 0 , title : 1 , author : 1 }}); // The document contains only title and author fields, not _id fieldsCopy the code
Aggregation operations
Db.col. aggregate([{$group : {
_id : <groupby-key>,
<new-key> : {$sum : <key>}
}
}
])
db.col.aggregate([{$group:{_id : <groupby-key>,<new-key>:{$avg:<key>}}}])// Average db.col.aggregate([{$group:{_id : <groupby-key>,<new-key>:{$min:<key>}}}]) db.col.aggregate([{$group:{_id : <groupby-key>,<new-key>:{$max:<key>}}}]) db.col.aggregate([{$group:{_id : <groupby-key>,<new-key>:{$first: < key >}}})/db/get the first document data col. Aggregate ([{$group : {_id : <groupby-key>,<new-key> : {$lastDb.orders. Aggregate ([{db.orders. Aggregate ([{db.orders.$match: {
date: {
$gte: new Date(new Date().getTime() - 1000 * 3600 * 24 * 7),
$lt: new Date(),
},
},
},
{
$group: {
_id: "$status",
count: {
$sum: 1,},},},]); // First match the data from a week ago, group the data based on the status field, create a field count to total the number of each groupCopy the code
5 Updating documents
-
The official document: docs.mongodb.com/manual/refe…
-
update(<query>,<update>,<options>)
-
Remove (
) : delete according to the condition
> db.posts.update({"title":"Monster Hunter World Review"}, {$set: {"rank": 10}}); > db.posts.update({"tag":"it"}, {$set: {"rank": 60}}, {multi: true});
> db.posts.remove({"title":"It's actually more fun to be creative than ambitious."})
Copy the code
update
- $inc – additive
- $the mul – multiplication
- $rename – renamed
- $set — Adds or changes
- $unset — Field deletion
> db.posts.update({title:"Monster Hunter World Review"}, {$inc: {rank: 1}});
> db.posts.update({title:"Monster Hunter World Review"}, {$rename: {"rank": "score"}});
Copy the code
options
- $upsert — If there is an update, if there is no append
- $multi – Whether to enable multiple selection
> db.posts.update({title:"It's actually more fun to be creative than ambitious."}, {title:"It's actually more fun to be creative than ambitious."."rank": 5,"tag":"game"}, {upsert:true});
> db.posts.update({title:"Monster Hunter World Review"}, {$unset: {"istop": true}});
Copy the code
Vi Using indexes
Use indexes to speed up queries
db.col.getIndexes(); Db.col.createindex ({<key>:<);type>}); Db.col.createindex ({<key>:<);type>,<key>:<type>}); Db.col.createindex ({<key>:<) db.col.createIndex({<key>:<)type>,"unique":true}); Db.col. dropIndex({<key>:<) db.col.dropIndex({<key>:<)type>}); Db.col. createIndex({rank:-1}); > db.col.dropIndex({rank:-1});Copy the code
7 Rights Management
Create the role
Switch to the database first, then create the role. Role is the role type, and DB specifies the database
> use admin
> db.createUser({
user:"admin".pwd:"123456",
roles:[{role:'root',db:admin}]
});
Copy the code
The configuration file
/bin/mongod.cfg
security:authorization enabled
Copy the code
Mongoserver needs to be restarted before configuring the file to take effect
The connection
mongo admin -u admin -p 123456
//or
mongo admin
db.auth("admin"."123456")
Copy the code
other
DropUser (<user_name>)// Delete db. UpdateUser (<user_name>,{pwd: <pwd>})// Change the passwordCopy the code
8 Backup and Restoration
- Mongodump: backup
- Mongorestore: restore