MongoDB聚合方法:aggregate() 语法:db.collection_name.aggregate(AGGREGATE_OPERATION) 管道:MongoDB的聚合管道将文档在一个管道处理完毕的结果传递给下一个管道处理,管道操作是可以重复的 常用管道:
# 事例数据{ "_id": ObjectId("5e5e05ef88f52a1c16bbff0f"), "url": "https://www.baidu.com/", "web_name": "百度", "click_num": 605, "year": 2019}
1 # 输出文档中除了web_name和click_num外,还包含默认的 _id 域 2 db.test_study.aggregate([ 3 { 4 $project: { 5 web_name: "$web_name", 6 click_num: "$click_num" 7 } 8 } 9 ])10 11 12 # 设置 _id:0 输出文档中只包括 web_name 和 click_num,不包含 _id 域13 db.test_study.aggregate([14 {15 $project: {16 _id:0,17 web_name: "$web_name",18 click_num: "$click_num"19 }20 }21 ])
# 事例数据
{ "_id": 1, "title": "789", "author": { "last": "Li", "first": "Lucy", "country": "China" }, "copies": 5, "lastModified": "2019-07-28"}
需求:输出 title,author.country
db.test.aggregate([{ $project: { _id:0, title: "$title", author_country: "$author.country" }}])
db.test.aggregate([{ $project: { "_id":0, "copies": 0, "author.country": 0 }}])
注意:
"copies" 要加双引号