UK Day46 MongoDB 聚合(aggregate)操作

前置知识

  • 聚合英文:aggregate

  • 聚合的方法:aggregate()

  • 聚合作用:求给定数据的总和、平均值等。

  • 聚合语法:db.集合名.aggregate(聚合操作)

具体例子

  1. 往集合里面插入多个文档:
db.Article.insertMany([
{
	book_name: 'MongoDB',
	description: 'MongoDB is a NoSQL database.',
	author: 'Alice',
	evaluation: 100,
	tags: ['Database', 'NoSQL']
},{
	book_name: 'MySQL',
	description: 'MySQL is a relational database.',
	author: 'Alice',
	evaluation: 90,
	size:{ height:10, weight:15}
},{
	book_name: 'PostgreSQL',
	description: 'pqsql balabalalalalala.',
	author: 'John',
	evaluation: 80
}])
  1. 执行 db.Article.aggregate([{$group : {_id: "$author", article_number: {$sum: 1}}}]) ,统计出每个人写的文章数

  2. 给Alice多增加一篇文章 把mysql的作者mike->Alice:db.Article.update({book_name: 'MySQL'},{$set:{author: 'Alice'}})

  3. 再次执行 db.Article.aggregate([{$group : {_id : "$author", article_number : {$sum : 1}}}]) 命令,观察变化。

参考

https://www.runoob.com/mongodb/mongodb-aggregate.html2.

原文地址:https://www.cnblogs.com/OFSHK/p/15546995.html