当前位置:网站首页>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
边栏推荐
- mongodb基础操作之聚合操作、索引优化
- Management system itclub (medium)
- Penetration learning - shooting range chapter -dvwa shooting range detailed introduction (continuous updating - currently only the SQL injection part is updated)
- Consumer finance app user insight in the first quarter of 2022 - a total of 44.79 million people
- Using xgboost with tidymodels
- 「R」使用ggpolar绘制生存关联网络图
- Gartner focuses on low code development in China how UNIPRO practices "differentiation"
- OData - SAP S4 OP 中使用SAP API Hub 的API
- 结构化机器学习项目(一)- 机器学习策略
- Crawler notes (2) - parse
猜你喜欢

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

Spark BUG实践(包含的BUG:ClassCastException;ConnectException;NoClassDefFoundError;RuntimeExceptio等。。。。)

Deep learning has a new pit! The University of Sydney proposed a new cross modal task, using text to guide image matting

Livox Lidar+海康Camera实时生成彩色点云

"I make the world cooler" 2022 Huaqing vision R & D product launch was a complete success

改善深层神经网络:超参数调试、正则化以及优化(三)- 超参数调试、Batch正则化和程序框架

Solution to the error of VMware tool plug-in installed in Windows 8.1 system

First knowledge of the second bullet of C language

Vue+mysql login registration case

對話喬心昱:用戶是魏牌的產品經理,零焦慮定義豪華
随机推荐
元气森林的5元有矿之死
渗透学习-靶场篇-dvwa靶场详细攻略(持续更新中-目前只更新sql注入部分)
Is flush stock trading software reliable?? Is it safe?
Livox lidar+ Hikvision camera real-time 3D reconstruction based on loam to generate RGB color point cloud
ABAP随笔-物料主数据界面增强-页签增强
Ellipsis after SQLite3 statement Solutions for
Stunned! The original drawing function of markdown is so powerful!
netERR_ CONNECTION_ Refused solution
Brief introduction to game phone platform
Re recognize G1 garbage collector through G1 GC log
Crawler notes (2) - parse
Kill the general and seize the "pointer" (Part 2)
OData - SAP S4 OP 中使用SAP API Hub 的API
Is it safe for GF futures to open an account?
Deep learning has a new pit! The University of Sydney proposed a new cross modal task, using text to guide image matting
Web worker introduction and use cases
Liuleifeng, a "good man in Guangzhou" in the first quarter of 2022, has a strong sense of integrity and food safety
Livox lidar+apx15 real-time high-precision radar map reproduction and sorting
爬虫笔记(3)-selenium和requests
初识C语言 第二弹