当前位置:网站首页>Mongodb aggregation operation summary
Mongodb aggregation operation summary
2022-07-04 22:37:00 【cui_ yonghua】
1. Role of aggregation operation
MongoDB Middle polymerization (aggregate) It's mainly used to process data ( Such as the statistical average , Make a peace, etc ), And return the calculated data result .
It's kind of similar SQL Statement count(*), sum(), avg().
2. aggregate() Method
MongoDB The method of aggregation used in aggregate().
Grammar format :db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Case study : Count the number of articles written by each author , Use aggregate() The calculation results are as follows
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$sum : 1}}}])
# similar SQL sentence
select by_user, count(*) from mycol group by by_user;
In the example above , Through fields by_user Fields group data , And calculate by_user The sum of the same values of the fields .
3. Common aggregate expressions
1、$sum Calculate the sum .
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$sum : "$likes"}}}])
1、$avg Calculate average
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$avg : "$likes"}}}])
1、$min Get the minimum value of all documents in the collection .
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$min : "$likes"}}}])
1、$max Get the maximum value of all documents in the collection .
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$max : "$likes"}}}])
1、$push Add values to an array , Does not determine whether there are duplicate values .
db.mycol.aggregate([{
$group : {
_id : "$by_user", url : {
$push: "$url"}}}])
1、$addToSet Add values to an array , Will determine whether there are duplicate values , If same value already exists in array , Do not join .
db.mycol.aggregate([{
$group : {
_id : "$by_user", url : {
$addToSet : "$url"}}}])
1、$first Get the first document data according to the sorting of resource documents .
db.mycol.aggregate([{
$group : {
_id : "$by_user", first_url : {
$first : "$url"}}}])
1、$last Get the last document data according to the sorting of resource documents
db.mycol.aggregate([{
$group : {
_id : "$by_user", last_url : {
$last : "$url"}}}])
4. The concept of pipes
Pipes in Unix and Linux It is generally used to take the output of the current command as the parameter of the next command .
MongoDB The polymerization pipeline of will MongoDB The document passes the result to the next pipeline after processing one pipeline . Pipeline operation can be repeated .
expression : Process input documents and output . Expressions are stateless , Only documents that can be used to calculate the current aggregate pipeline , Can't process other documents .
Schematic diagram of polymerization pipeline :
amount to Sql sentence : Select cust_id,sum(amount)as total from orders where status= "A"
Several operations commonly used in aggregation framework :
$project: Modify the structure of the input document . Can be used to rename 、 Add or remove fields , It can also be used to create calculation results and nested documents .$match: For filtering data , Output only documents that meet the criteria .$match Use MongoDB Standard query operation .$limit: Used to restrict MongoDB The number of documents returned by the aggregation pipeline .$skip: Skip the specified number of documents in the aggregation pipeline , And return the remaining documents .$unwind: Split an array type field in the document into multiple fields , Each contains a value in the array .$group: Group documents in a collection , Can be used for statistical results .$sort: Sort the input documents and output .$geoNear: Output ordered documents close to a geographic location .
Case study 1:$project
db.article.aggregate({
$project: {
title: 1, author: 1,}});
# By default _id Fields are included , If you want to exclude _id That's how it works
db.article.aggregate({
$project: {
_id : 0 ,title: 1 ,author: 1}});
Case study 2:$match Case study , Get score greater than 70 Less than or equal to 90 Record , Then send the eligible records to the next stage $group The pipeline operator handles .
db.articles.aggregate([{
$match : {
score : {
$gt : 70, $lte : 90 } } },{
$group: {
_id: null, count: {
$sum: 1 } } }]);
Case study 3: after $skip After the pipeline operator is processed , The first five documents are " Filter " fall .
db.article.aggregate({
$skip : 5 });
5. SQL Corresponding to aggregation
| SQL The term 、 function 、 Concept | MongoDB Aggregation operation |
|---|---|
| WHERE | $match |
| GROUP BY | $group |
| HAVING | $match |
| SELECT | $project |
| ORDER BY | $sort |
| LIMIT | $limit |
| SUM() | $sum |
| COUNT() | $sum |
| join | $lookup (3.2 Version added ) |
边栏推荐
- Service online governance
- 面试必备 LeetCode 链表算法题汇总,全程干货!
- [acwing] solution of the 58th weekly match
- 好用app推荐:扫描二维码、扫描条形码并查看历史
- The table is backed up in ODPs. Why check m in the metabase_ Table, the logical sizes of the two tables are inconsistent, but the number of
- Enabling digital economy Fuxin software attends the BRICs high level Forum on Sustainable Development
- Tla+ introductory tutorial (1): introduction to formal methods
- 繁华落尽、物是人非:个人站长该何去何从
- LOGO special training camp section I identification logo and Logo Design Ideas
- LOGO特訓營 第一節 鑒別Logo與Logo設計思路
猜你喜欢

将QA引入软件开发生命周期是工程师要遵循的最佳实践

Radio and television Wuzhou signed a cooperation agreement with Huawei to jointly promote the sustainable development of shengteng AI industry

达梦数据凭什么被称为国产数据库“第一股”?

Locust performance test - environment construction and use

How to transfer to software testing, one of the high paying jobs in the Internet? (software testing learning roadmap attached)

Tla+ introductory tutorial (1): introduction to formal methods

Éducation à la transmission du savoir | Comment passer à un test logiciel pour l'un des postes les mieux rémunérés sur Internet? (joindre la Feuille de route pour l'apprentissage des tests logiciels)

安装人大金仓数据库

都说软件测试很简单有手就行,但为何仍有这么多劝退的?

LOGO特训营 第一节 鉴别Logo与Logo设计思路
随机推荐
10 schemes to ensure interface data security
醒悟的日子,我是怎么一步一步走向软件测试的道路
ACM multimedia 2022 | counterfactual measurement and elimination of social prejudice in visual language pre training model
Close system call analysis - Performance Optimization
LOGO特训营 第三节 首字母创意手法
La prospérité est épuisée, les choses sont bonnes et mauvaises: Où puis - je aller pour un chef de station personnel?
【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
堆排序代码详解
蓝队攻防演练中的三段作战
leetcode 72. Edit Distance 编辑距离(中等)
With this PDF, we finally got offers from eight major manufacturers, including Alibaba, bytek and Baidu
POM in idea XML dependency cannot be imported
串口数据帧
PostgreSQL JOIN实践及原理
PostgreSQL server programming aggregation and grouping
Google Earth Engine(GEE)——以MODIS/006/MCD19A2为例批量下载逐天AOD数据逐天的均值、最大值、最小值、标准差、方差统计分析和CSV下载(北京市各区为例)
好用app推荐:扫描二维码、扫描条形码并查看历史
Logo special training camp Section V font structure and common design techniques
Éducation à la transmission du savoir | Comment passer à un test logiciel pour l'un des postes les mieux rémunérés sur Internet? (joindre la Feuille de route pour l'apprentissage des tests logiciels)
傳智教育|如何轉行互聯網高薪崗比特之一的軟件測試?(附軟件測試學習路線圖)