node.js - mongoose 中的聚合查询
问题描述
这是要求我编写一个简单的聚合查询来显示数据的问题,我有点困惑。你能帮我看看这段代码吗?
如何从以下位置查询数据:
{
"_id": "5af50e729ba1ae0056dbb436",
"__v": 0,
"asset_id": "CHMHCj-sqJdbPwDs_6Y4_Q",
"asset_type": "youtube_channel",
"created_at": "2018-05-11T03:30:58.487Z",
"schema_version": 1,
"stat": "posts_30d",
"updated_at": "2018-05-11T03:30:58.487Z",
"value": "0"
},
至:
[
{
_id: '<channel_id>',
subscribers: [
{value: Number, date: Date},
// most recent 10 records
],
posts_30d: [
{value: Number, date: Date},
// most recent 10 records
]
},
]
channel_id 是asset_id,posts_30d 是统计值。stat 值将是“stat”:“posts_30d”或“stat”:“subscribers”。新数据将根据asset_id和stat值显示。
我曾尝试使用 unwind 和 project,但它看起来不一样。另外,我使用“限制”来限制帖子的数量,但结果显示每个应该有 10 个,但总共显示 10 个。
db.Stats.aggregate([
{ $unwind: "$stat" },
{ $sort: { updated_at: -1 } },
{ $limit : 5 },
{
$project: {
asset_id: 1,
value: 1,
updated_at: 1,
stat: 1
}
},
{
$group: {
_id: "$asset_id",
sub: {
$push: {
value: "$value",
date: "$updated_at"
}
}
}
}
]).exec(function(err, found) {
// Log any errors if the server encounters one
if (err) {
console.log(err);
}
// Otherwise, send the result of this query to the browser
else {
res.json(found);
}
});
解决方案
推荐阅读
- django - 如何使用 datetimes() 查询集函数在 Django 中使用 count 进行注释
- java - java - 如何以以下模式dd/MM/yyyy在java中获取今天的日期?
- javascript - 在 JS 中使用 Object.keys 遍历多个嵌套的 JSON
- c# - 使 AutoMapper 重用以前映射的实例
- r - 减去相似的列名 R
- windows - 我该怎么做才能让 RestartDialogEx 显示我的提示?
- php - jquery每个输入多量计算得到动态形式的NaN
- google-apps-script - 如何在一个 Google Sheets 工作簿中的多个选项卡上执行相同的功能?
- genexus - Genexus 与 Ssas 的集成
- javascript - 全局变量/全局命名空间的 JavaScript 策略