Wernfried 的答案非常接近我所需要的解决方案。这是我的最终方法:
db.collection.aggregate([
{
$group: {
_id: null,
data: {
$push: "$$ROOT",
},
},
},
{
$set: {
data: {
$map: {
input: {
$range: [0, period],
},
as: "idx",
in: {
date: {
$subtract: [
moment().toDate(),
{ $multiply: [1000 * 60 * 60 * 24, "$$idx"] },
],
},
window: {
$filter: {
input: "$data",
cond: {
$and: [
{
$lte: [
"$$this.createdAt",
{
$subtract: [
moment().toDate(),
{ $multiply: [1000 * 60 * 60 * 24, "$$idx"] },
],
},
],
},
{
$gte: [
"$$this.createdAt",
{
$subtract: ["$date", 1000 * 60 * 60 * 24 * 90],
},
],
},
],
},
},
},
},
},
},
},
},
{
$set: {
data: {
$map: {
input: "$data",
in: {
date: "$$this.date",
score: {
$avg: "$$this.window.value",
},
},
},
},
},
},
])
其中 period 是我需要移动平均线的天数。这将为 period = 7 产生以下响应:
[
{ date: 2021-08-11T21:49:49.097Z, score: 6.513605442176871 },
{ date: 2021-08-10T21:49:49.097Z, score: 6.513605442176871 },
{ date: 2021-08-09T21:49:49.097Z, score: 6.556818181818182 },
{ date: 2021-08-08T21:49:49.097Z, score: 6.556818181818182 },
{ date: 2021-08-07T21:49:49.097Z, score: 6.556818181818182 },
{ date: 2021-08-06T21:49:49.097Z, score: 6.556818181818182 },
{ date: 2021-08-05T21:49:49.097Z, score: 6.497863247863248 }
]