当前位置:网站首页>Aggregation and index optimization of mongodb basic operations
Aggregation and index optimization of mongodb basic operations
2022-06-27 22:51:00 【wr456wr】
mongodb Aggregation of basic operations 、 Index optimization
Better reading experience https://www.wolai.com/wrMtYWKdkzKYjoWM1i64qu
Catalog
Aggregation operation
Polymerization pipeline operation
$group Group documents in the collection , Facilitate subsequent statistical results
$limit Used to limit the MongoDB The number of documents returned by the aggregation pipeline
$match For filtering data , Output only documents that meet the criteria
$sort Sort the input documents first , Then the output
$project Used to modify the structure of the input document ( increase , Delete fields, etc ) And name
$skip Skip the specified number of documents in the aggregation pipeline , And return the remaining documents
Specific syntax :
# $group
db.COLLECTION_NAME.aggregate([{$group:{<key1>:"$<key2>"}}]).pretty()
# $limit
db.COLLECTION_NAME.aggregate({$limit: integer }).pretty()
# $match
db.COLLECTION_NAME.aggregate([{$match:{<key>:<value>}}]).pretty()
# $sort, -1 Representation of descending order , 1 Expressing ascending order
db.COLLECTION_NAME.aggregate([{$sort:{<key>:-1 or 1}}]).pretty()
# $project
db.COLLECTION_NAME.aggregate([{$project:{<key>:<value>}}]).pretty()
# $skip
db.COLLECTION_NAME.aggregate({$skip: integer }).pretty()
group: Press... For the documents in the collection userid Grouping
db.firstCollection.aggregate([{$group:{"_id": "$userid"}}]).pretty()
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-xOzMu1nz-1654414283983)(image/image_r0sE7bJ0xd.png)]
limit: Specify that the collection only shows two documents
db.firstCollection.aggregate({$limit:2}).pretty()
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-rCo96aVa-1654414283984)(image/image_UNzxZXRVDa.png)]
match: Put... In the set nickname For Edward's documents
db.firstCollection.aggregate([{$match:{"nickname":" Edward "}}]).pretty()
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-yXiS6Ogh-1654414283985)(image/image_uNqDTLARAW.png)]
sort: Set the documents in the collection according to age Sort in descending order
db.firstCollection.aggregate([{$sort:{"age":-1}}]).pretty()
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-s9qqpvDc-1654414283985)(image/image_NibFuoUuUz.png)]
project: Show the documents in the collection , And none of the documents contain fields _id,articleid,content
db.firstCollection.aggregate([{$project:{ "_id":0, "articleid":0, "content":0}}]).pretty()
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-38uF2dpE-1654414283986)(image/image_h8qIgx1VBk.png)]
skip: Skip in collection _id by 5 Previous documents ( It doesn't contain 5), Show only _id by 5 Subsequent documents
db.firstCollection.aggregate({$skip:5}).pretty()
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-lo8dbf5G-1654414283986)(image/image_wiS_H6Zlji.png)]
Common pipe expressions and related descriptions
$sum Calculate the sum
$avg Calculate average
db.COLLECTION_NAME
$min Get the minimum value of all documents in the collection
$max Get the maximum value of all documents in the collection
$push Insert values into an array in the result document
$first Get the first document in the grouped document
$last Get the last document in the grouped document
Map-Reduce operation
MongoDB Provide Map-Reduce To perform aggregation operations .
db.firstCollection.mapReduce(
function() {emit(this.nickname, 1);},
function(key,values) {return Array.sum(values)},
{
query:{state:"1"}, out:"comment_total"
}
)
Output results :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-0Ztywsa6-1654414283986)(image/image_OV4qxjjBxd.png)]
result: Save the result set
timeMillis: perform Map-Reduce Time spent in operation
input: If the filter conditions are met, it is input to map Number of documents for the function
emit: stay map Function emit() The number of times the method was called , That is, the number of documents in the collection that meet the conditions
output: Number of documents in the result set
ok: Judgment execution Map-Reduce Successful operation , If the execution is successful, it displays 1, Instead, use err Express
Optimize queries using indexes
MongoDB The index of can be divided into 6 Kind of : Single field index 、 Composite index 、 Multi key index 、 Geospatial index 、 Text index and Hashemite index
By default ,MongoDB All sets in _id There is an index on each field . because MongoDB You can traverse the index from any direction , So for single field indexing and sorting operations , The sort order of the index entries is not important .
If field of the document is array type , Then each field is an element in the array ,MongoDB An index will be created for each element in the array , So it is called multi key index .
Index operation
Look at the index
db.COLLECTION_NAME.getIndexes()
Query the collection firstCollection Index in
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-YNhERXma-1654414283987)(image/image_MeZYME4RV9.png)]
Among the results returned are 4 A field , Namely v、key、name as well as ns, Which field v Indicates the version number of the indexing engine , Field key Indicates the field to which the index is added , The default is _id, Its value is 1 Indicates that the index is sorted in ascending order ; Field namne Represents the name of the index , That is, the field plus _, namely _id_; Field ns Represents the namespace of the index store , That is database test Set firstCollection in .
View index size
db.COLLECTION_NAME.totalIndexSize()
Query the collection firstCollection Index size in
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-gUghtxIU-1654414283987)(image/image_5Ey6xuIt8-.png)]
Create index
db.COLLECTION_NAME.createIndex(keys,options)
keys: The data type of this parameter is document type , Is a document that contains fields and values , Where the field is the index key , The value is the index type that describes the field . If the specified field is an ascending index , The specified value is 1, conversely , The specified value is -1
options: The data type of this parameter is document type , It's optional , A document containing a set of options that control index creation . Common options are unique and name, One option unique Describe whether the index is unique , If the value is true, Create a unique index , The default value is false; Options name Describes the name of the index created , If no name is specified ,MongoDB An index name will be generated by connecting the field name and sort order of the index
In collection firstCollection Create a single field index in , That is to say userid Create an index on the field of
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-8IVZOejw-1654414283988)(image/image_gaPyPoR1m3.png)]
Look at the index
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-vSc25naP-1654414283988)(image/image_GiAPW5xDnA.png)]
Create composite index , That is to say userid and nickname At the same time, create an index on the field of
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-z2QminVK-1654414283988)(image/image_2kQzv0rkOJ.png)]
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-WLKuYimQ-1654414283989)(image/image_2n_CHtl03S.png)]
Delete index
# Delete a single index
db.COLLECTION_NAME.dropIndex(index)
# Delete all indexes
db.COLLECTION_NAME.dropIndexes()
Delete userid Indexes
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-uogGGSXJ-1654414283989)(image/image_Jl5Rj-3Y0d.png)]
Delete all indexes
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-XQdQdSC6-1654414283989)(image/image_Q-v1W_K65K.png)]
Indexes _id_ By default , Cannot delete , Only non fields can be deleted _id The index of
Better reading experience https://www.wolai.com/wrMtYWKdkzKYjoWM1i64qu
边栏推荐
- "I make the world cooler" 2022 Huaqing vision R & D product launch was a complete success
- 跟着存档教程动手学RNAseq分析(一)
- Zabbix6.0 upgrade Guide - how to synchronize database upgrades?
- Login credentials (cookie+session and token token)
- 批量处理-Excel导入模板1.1-支持多Sheet页
- 99 multiplication table - C language
- Introduce you to ldbc SNB, a powerful tool for database performance and scenario testing
- Consumer finance app user insight in the first quarter of 2022 - a total of 44.79 million people
- Solution to the error of VMware tool plug-in installed in Windows 8.1 system
- Dialogue with Qiao Xinyu: the user is the product manager of Wei brand, and zero anxiety defines luxury
猜你喜欢

對話喬心昱:用戶是魏牌的產品經理,零焦慮定義豪華

How to use RPA to achieve automatic customer acquisition?

About the SQL injection of davwa, errors are reported: analysis and verification of the causes of legal mix of settlements for operation 'Union'
Conversion between flat array and JSON tree

Solve the problem that the virtual machine cannot be connected locally

99 multiplication table - C language

Passerelle de service pour les microservices

医美大刀,砍向00后

Livox Lidar+APX15 实时高精度雷达建图复现整理

《7天学会Go并发编程》第六天 go语言Sync.cond的应用和实现 go实现多线程联合执行
随机推荐
游戏手机平台简单介绍
Stunned! The original drawing function of markdown is so powerful!
Hiplot 在線繪圖工具的本地運行/開發庫開源
MySQL greater than less than or equal to symbol representation
同花顺炒股软件可靠吗??安全嘛?
Gartner focuses on low code development in China how UNIPRO practices "differentiation"
资深猎头团队管理者:面试3000顾问,总结组织出8大共性(茅生)
Management system itclub (Part 1)
Is it safe for GF futures to open an account?
Bibliothèque d'exploitation / de développement locale open source pour l'outil de dessin en ligne hiplot
Oracle obtains the beginning and end of the month time, and obtains the beginning and end of the previous month time
Service gateway of microservices
爬虫笔记(1)- urllib
信通院举办“业务与应用安全发展论坛” 天翼云安全能力再获认可
Spark BUG實踐(包含的BUG:ClassCastException;ConnectException;NoClassDefFoundError;RuntimeExceptio等。。。。)
Introduction to ARCS Model
Penetration learning - shooting range chapter -dvwa shooting range detailed introduction (continuous updating - currently only the SQL injection part is updated)
「R」 Using ggpolar to draw survival association network diagram
About the SQL injection of davwa, errors are reported: analysis and verification of the causes of legal mix of settlements for operation 'Union'
个人TREE ALV 模版-加快你的开发