MongoDB——聚合管道之$match操作

x33g5p2x  于2022-04-22 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(352)

一、$ match的概述

  • $ match用于对文档进行筛选,之后可以在得到的文档子集上做聚合,$ match可以使用除了地理空间之外的所有常规查询操作符,在实际应用中尽可能将$ match放在管道的前面位置。这样有两个好处:一是可以快速将不需要的文档过滤掉,以减少管道的工作量;二是如果再投射和分组之前执行$match,查询可以使用索引。
  • 筛选管道操作和其他管道操作配合时候时,尽量放到开始阶段,这样可以减少后续管道操作符要操作的文档数,提升效率。

二、数据准备

  • 准备数据集,执行脚本
var tags = ["nosql","mongodb","document","developer","popular"];
var types = ["technology","sociality","travel","novel","literature"];
var books=[];
for(var i=0;i<50;i++){
	var typeIdx = Math.floor(Math.random()*types.length);
	var tagIdx = Math.floor(Math.random()*tags.length);
	var tagIdx2 = Math.floor(Math.random()*tags.length);
	var favCount = Math.floor(Math.random()*100);
	var username = "xx00"+Math.floor(Math.random()*10);
	var age = 20 + Math.floor(Math.random()*15);
	var book = {
		title: "book-"+i, 
		type: types[typeIdx],
		tag: [tags[tagIdx],tags[tagIdx2]],
		favCount: favCount, 
		author: {name:username,age:age}
	};
	books.push(book)
}
db.books1.insertMany(books);

三、聚合管道之$ match操作示例

  • 查询books1集合中的数据
> db.books1.find()

  • 查询books1集合中type字段为technology的所有数据
db.books1.aggregate([{$match:{type:"technology"}}])

相关文章

微信公众号

最新文章

更多