在demo数据库中完成下列操作:
1.在demo库中col集合中,要求以书名title分组,求每种书的likes总数。
db.test.aggregate([{
$group: { _id: "$title",
"books_count": {$sum:"$likes"}
}
}])
Run:
{ _id: 'MongoDB 教程', books_count: 300 }
{ _id: 'MongoDB 实践与应用', books_count: 400 }
{ _id: 'MongoDB 高级编程', books_count: 500 }
{ _id: 'MongoDB 数据库开发基础实践', books_count: 300 }
2.在demo库中col集合中,要求按照书籍的标题(title)进行分组,并求字段likes的平均值。
db.test.aggregate([{$group: { _id: "$title","books_count": {$avg:"$likes"}}}])
Run:
{ _id: 'MongoDB 教程', books_count: 150 }
{ _id: 'MongoDB 数据库开发基础实践', books_count: 300 }
{ _id: 'MongoDB 实践与应用', books_count: 400 }
{ _id: 'MongoDB 高级编程', books_count: 500 }
3.在demo库中的对col集合中,查询likes大于50且按title分组统计各组书籍的册数counter。
db.test.aggregate(
[
{$match: {likes:{$gt:50}}},
{$group: { _id: "$title","books_count": {$sum:1}}}
])
Run:
{ _id: 'MongoDB 教程', books_count: 2 }
{ _id: 'MongoDB 数据库开发基础实践', books_count: 1 }
{ _id: 'MongoDB 实践与应用', books_count: 1 }
{ _id: 'MongoDB 高级编程', books_count: 1 }
4.在demo库中对col集合中,查询likes小于600 且按书籍名称title分组,
统计各组书籍的册数counter,且结果要按照书籍册数降序排序。
db.test.aggregate([{/**
* query: The query in MQL.
*/
$match: {
likes:{$lt:600}
}},
{$group:{
"_id":"$title",
"books_count":{$sum:1}
}
},
{$sort: {
"books_count":-1
}}])
Run:
{ _id: 'MongoDB 实践与应用', books_count: 1 }
{ _id: 'MongoDB 高级编程', books_count: 1 }
{ _id: 'MongoDB 数据库开发基础实践', books_count: 1 }
{ _id: 'MongoDB 教程', books_count: 2 }
5.在demo库中对col集合中,查询likes大于50且按书籍名称title分组,
统计各组书籍的册数,并显示投影为counter字段,结果要按照counter字段升序排序,
限制输出3条查询结果,并跳过第1条记录。
db.test.aggregate([{/**
* query: The query in MQL.
*/
$match: {
likes:{$gt:50}
}},
{$group:{
"_id":"$title",
"counter":{$sum:1}
}},
{
$sort: {
"counter":1
}},
{/**
* Provide the number of documents to skip.
*/
$skip: 1}])
Run:
{ _id: 'MongoDB 实践与应用', counter: 1 }
{ _id: 'MongoDB 高级编程', counter: 1 }
{ _id: 'MongoDB 教程', counter: 2 }
!!!!!!
6.在demo库中对col集合中by字段进行拆分。by中数据的格式为:by:[{first:'Obama'},{second:'Trump'}]。(提示:使用$unwind聚合操作符)
db.test.aggregate(
[
{
$unwind: {
path: "$by",
preserveNullAndEmptyArrays:true
}}
]
)
7.对col集合中的前三条文档按照title分组,统计likes值的总和。
db.test.aggregate([{
$group: {
_id: "$title",
"SumCount": {
$sum:"$likes"
}
}
},
{
$limit: 3}
])
Run:
{ _id: 'MongoDB 教程', SumCount: 300 }
{ _id: 'MongoDB 实践与应用', SumCount: 400 }
{ _id: 'MongoDB 高级编程', SumCount: 500 }
MapReduce:在Mongodb4.2版本后已经被弃用!!!!!!
8.使用mapReduce(),在demo库中对col集合查询likes值在[100,400]之间的文档,
并按照title分组统计每种书的册数,并保存在col_counter集合中。
db.test.mapReduce(
function(){emit(this.title,1)},
function(key,values){return Array.sum(values)},
{query:{likes:{$gt:100,$lt:400}},
out:"col_count"}
)
9.使用mapReduce(),在demo库中对col集合查询likes值在[100,400]之间的文档,
并按照title分组统计每种书的likes值的总和,并保存在col_total集合中。
db.test.mapReduce(
function(){emit(this.title,this.likes)},
function(key,value){return Array.sum(value)},
{query:{likes:{$gt:100,$lt:400}}, out:"col_total"}
)