【发布时间】:2019-10-23 07:46:39
【问题描述】:
我正在尝试在 js 文件中查找书籍的平均价格。
到目前为止,我已经计算出了总共 4 本书的数量(查询如下所示)
db.bookshop.aggregate([ {"$unwind":"$book"},
{"$project":{"price":"$book.book","_id":0}},
{"$count":"average price of books"} ]).pretty();
此查询的输出:
{ "average price of books" : 4 }
这是我试图找出所有不起作用的书籍的总价格。我已经这样做了,因为我假设找到平均值是总和除以计数。
db.bookshhop.aggregate([ {$group: {_id: null,"TotalAmount":
{$sum: "$book.price"}}}] );
我在查找所有图书价格的平均价格时遇到问题。我怎样才能做到这一点?谢谢
这些是书的js记录:
db.bookshop.insert( {
"_id":"185.3.16",
"book": {
"callnum":"185.3.16",
"isbn":"1-292-06118-9",
"title":"Database Systems",
"authors":[
{
"fname":"Thomas",
"lname":"Connolly"},
{
"fname":"Carolyn",
"lname":"Begg"}
],
"publisher":"Pearson Pty Ltd",
"year":2015,
"price":136.99,
"topic":"Computer Science",
"description":"This is the 6th edition. You can register online to access the examples",
"keywords":["Database", "XML", "Distributed"]
}
});
db.bookshop.insert( {
"_id":"163.24.12",
"book": {
"callnum":"163.24.12",
"isbn":"1-123-456-810",
"title":"Core Java",
"authors":[
{
"fname":"Horstmann",
"lname":"Cornell"}
],
"publisher":"PH Pty Ltd",
"year":2012,
"price":142.90,
"topic":"Computer Science",
"description":"It covers JAVA programming and JAVA script",
"keywords":["JAVA", "XML", "Script"]
}
});
db.bookshop.insert( {
"_id":"123.45.67",
"book": {
"callnum":"123.45.67",
"isbn":"1-123-456-789",
"title":"Algorithms",
"authors":[
{
"fname":"James",
"lname":"Bond"},
{
"fname":"Harry",
"lname":"Potter"},
{
"fname":"William",
"lname":"Stallings"}
],
"publisher":"Pearson Pty Ltd",
"year":2013,
"price":65.85,
"topic":"Computer Science",
"description":"It contains algorithms and their applications. You can download examples from the website"
}
});
db.bookshop.insert( {
"_id":"134.41.33",
"book": {
"callnum":"134.41.33",
"isbn":"1-213-431-770",
"title":"C++ Programming",
"authors":[
{
"fname":"Larry",
"lname":"Peterson"}
],
"publisher":"Pearson Pty Ltd",
"year":2010,
"price":74.90,
"topic":"Computer Science",
"description":"C++ programming and its applications",
"keywords":["C++", "Class", "Overloading", "Inheritance"]
}
});
【问题讨论】: