美文网首页
MongoDB Compass Aggregation的几个应用

MongoDB Compass Aggregation的几个应用

作者: Rainbow想喝奶茶 | 来源:发表于2021-10-29 16:14 被阅读0次

聚合管道,是对查询的数据进行聚合等操作,在MongoDB Compass中,此页面可以创建多个聚合操作进行数据处理,也可以保存管道方便后续使用,或者将管道结果保存为视图,(访问速度慢)。


聚合管道操作页面

操作步骤

  1. select选定聚合操作后,会出现默认样例


    默认样例
  2. 在左侧填写具体聚合条件后,启动自动预览,右侧会实时出现预览文档。


    具体聚合条件
  3. 点击已有管道右侧“+”或下方“ADD STAGE”创建新的聚合管道。 聚合按顺序从上至下执行,每一个聚合操作均可以查看截至当前操作的预览文档结果。聚合操作右侧按钮若关闭,则跳过当前操作,点击删除,即可删除此操作。


    创建多个聚合操作

聚合操作举例

$match

{ $match: { <query> } }
#query输入想匹配的条件
$match

相当于`select * from table where score>=9 ';

$group

相当于psql 中的group by

{
  $group:
    {
      _id: <expression>, // Group By Expression
      <field1>: { <accumulator1> : <expression1> },
      ...
    }
 }
#_id 相当于sql中 group by 后面的字段 
#field 可选,添加累加器,作用于每个分组
$group
相当于SELECT score,count(*) FROM table GROUP BY score;

$project

{ $project: { <specification(s)> } }
#控制字段展示与否,1 or true代表展示,0 or false代表隐藏
$project
相当于SELECT score FROM table;

$count

{ $count: <string> }
#string中填写展示计算值的字段名称
$count
相当于select count(*) as num FROM table;

$sort

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }
#field:填写字段
#sort order 中的值 升序:1  降序:-1
$sort
相当于select score from table order by score desc;

$lookup

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
#from:需要join的集合名词
#localField:当前集合的字段名称
#foreignField:join的集合 与localField相同的字段名称
#as:join的集合中符合条件的数据字段值
$lookup

相当于select *,commentstid from table where commentstid in(select * from comments where tid=table.tid);

啊,就算是整理之前的知识点,也是有些秏心力啊~
明天考试加油~~~
11月是会努力学习的小透明,下个月见~~~~
自我记录,有错误欢迎指正

相关文章

网友评论

      本文标题:MongoDB Compass Aggregation的几个应用

      本文链接:https://www.haomeiwen.com/subject/cwbialtx.html