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

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

一、数据准备

  • 准备数据集,执行脚本
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);

二、聚合管道之$project操作示例

2.1、查询集合中的数据

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

  • 查询books1集合中的数据,格式化显示数据
> db.books1.find().pretty()

2.2、$project 可以表示投影操作, 将原始字段投影成指定名称

  • 将books1集合中的 title 投影成 name
db.books1.aggregate([{$project:{name:"$title"}}])

2.3、$project 可以灵活控制输出文档的格式,也可以剔除不需要的字段

  • title字段替换name,并且只显示type和author字段。(0表示不显示此字段,1表示显示此字段)
//_id:0表示不显示id字段;type:1表示显示type字段;author:1表示显示author字段
db.books1.aggregate([{$project:{name:"$title",_id:0,type:1,author:1}}])

2.4、$project 可以从嵌套文档中排除字段

  • 只显示author嵌套文档中的name字段
db.books1.aggregate([ {$project:{name:"$title",_id:0,type:1,"author.name":1}} ])

相关文章