当前位置:网站首页>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
边栏推荐
- Introduce you to ldbc SNB, a powerful tool for database performance and scenario testing
- [cloud based co creation] what is informatization? What is digitalization? What are the connections and differences between the two?
- Zabbix6.0 upgrade Guide - how to synchronize database upgrades?
- Crawler notes (1) - urllib
- Livox lidar+ Haikang camera generates color point cloud in real time
- Learn rnaseq analysis by following the archiving tutorial (I)
- 「R」使用ggpolar绘制生存关联网络图
- Structured machine learning project (II) - machine learning strategy (2)
- 网易云“情怀”底牌失守
- Basic data type and complex data type
猜你喜欢

C # QR code generation and recognition, removing white edges and any color

mysql操作入门(四)-----数据排序(升序、降序、多字段排序)

About the SQL injection of davwa, errors are reported: analysis and verification of the causes of legal mix of settlements for operation 'Union'

结构化机器学习项目(二)- 机器学习策略(2)

Infiltration learning - problems encountered during SQL injection - explanation of sort=left (version(), 1) - understanding of order by followed by string

Service gateway of microservices

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

《7天學會Go並發編程》第7天 go語言並發編程Atomic原子實戰操作含ABA問題

Do280openshift access control -- Security Policy and chapter experiment

PE买下一家内衣公司
随机推荐
Teach you how to print your own log -- how to customize log4j2 components
OpenSSL programming I: basic concepts
Livox Lidar+海康Camera实时生成彩色点云
渗透学习-靶场篇-dvwa靶场详细攻略(持续更新中-目前只更新sql注入部分)
Management system itclub (Part 1)
[microservices] (16) -- distributed transaction Seata
Day8 - cloud information project introduction and creation
Azure Kinect DK 实现三维重建 (jetson实时版)
Conversation Qiao Xinyu: l'utilisateur est le gestionnaire de produits Wei Brand, zéro anxiété définit le luxe
游戏手机平台简单介绍
ABAP essay - material master data interface enhancement - tab enhancement
[随笔]ME53N 增加按钮,调用URL
同花顺炒股软件可靠吗??安全嘛?
Structured machine learning project (I) - machine learning strategy
雪糕还是雪“高”?
Character interception triplets of data warehouse: substrb, substr, substring
【你真的会用ES吗】ES基础介绍(二)
微服務之服務網關
爬虫笔记(2)- 解析
Azure Kinect DK realizes 3D reconstruction (PC non real time version)