mongodb - MongoDB 平均聚合无法正常工作
问题描述
我是 NoSQL 数据库的新手。我想要的是显示title
,url
和avg(ratings)
. 示例数据如下所示:
{
"_id" : ObjectId("52b3833bd3e98582d2bfb628"),
"author" : {
"name" : "Graydon Hoare",
"email" : "graydon@gmail.com"
},
"title" : "Why Rust ditched pure functions",
"body" : "sth",
"url" : "http://thread.gmane.org/gmane.comp.lang.rust.devel/3674/focus=3855",
"date" : ISODate("2013-04-30T13:23:00.000Z"),
"starred" : 105,
"ratings" : [
3,
5,
3,
2,
4,
1,
3,
3,
3,
2,
3
],
"comments" : [
{
"user" : "tr0lltherapy",
"upVotes" : 18,
"downVotes" : 2,
"text" : "something",
"replies" : [
{
"user" : "thedeemon",
"upVotes" : 10,
"downVotes" : 0,
"text" : "something"
},
{
"user" : "mcandre",
"upVotes" : 0,
"downVotes" : 5,
"text" : "Performance? There are already a slew of performant languages. Assembler, C, C++, Go. What does Rust actually offer that's new and useful in this category, other than using my favorite abbreviation for the named function keyword, fn?"
},
{
"user" : "lacosaes0",
"upVotes" : 30,
"downVotes" : 6,
"text" : "Particular emphasis on memory safety."
}
]
},
{
"user" : "hypster",
"upVotes" : 30,
"downVotes" : 2,
"text" : "tl;dr everybody was type-fu fighting",
"replies" : [
{
"user" : "homoiconic",
"upVotes" : 15,
"downVotes" : 0,
"text" : "Here comes the Big Boss, Hu! Simon Peyton-Jones."
}
]
}
],
"tags" : [
"Rust",
"Computer",
"Programming"
],
"draft" : true,
"published" : true
}
我已经尝试了以下查询,但它不能正常工作并将null
值放在平均值中。我不知道我应该如何解决它。
db.getCollection('links').aggregate(
[
{
$match: {
"author.email": /@gmail.com$/
}
},
{
$project: {
_id: 0,
title: 1,
url: 1,
avgRatings: {
$avg: "$Ratings"
}
}
}
])
预期输出为:
title: "Why Rust ditched pure functions", url: "http://thread.gmane.org/gmane.comp.lang.rust.devel/3674/focus=3855",
avgRatings: 2.90
解决方案
你有一个错字,$Ratings
; $ratings
如下使用。聚合语法区分大小写。
db.getCollection('links').aggregate(
[
{
$match: {
"author.email": /@gmail.com$/
}
},
{
$project: {
_id: 0,
title: 1,
url: 1,
avgRatings: {
$avg: "$ratings"
}
}
}
])
推荐阅读
- pdf - 是否可以自动检查 PDF 是否遵循 PDF/UA 标准?
- shell - 如何在期望脚本的发送中使用 shell 命令的输出
- sql - SQL:根据表中保存的计算对每一行进行不同的计算
- android - 打开应用程序后 Flutter 崩溃
- python - 在 Vagrant 中安装 django-cron 时权限被拒绝
- db2 - DB2:LUW:Windows(OS) 无法调用 Java UDF
- pandas - 更改熊猫数据框的架构
- angular - 如何避免两次调用观察方法?
- python - 请求翻译时似乎未使用上传的词汇表
- c++ - 带有 C++ Builder 10.x 的 FASTMM 调试版本