mongodb - MongoDB - 根据前一项计算字段
问题描述
我有一个棘手的场景 - 我需要根据前一个字段的值计算额外的字段。我不知道如何以高性能的方式做到这一点。有什么想法吗?
数据:
{
_id: 1,
score: 66,
created_at: "2021-04-01"
},
{
_id: 2,
score: 12,
created_at: "2021-04-03"
},
{
_id: 3,
score: 7,
created_at: "2021-04-06"
}
我想要达到的目标
{
_id: 1,
score: 66,
total_score: 66 // The most oldest item, so total score is the same as current score
created_at: "2021-04-01"
},
{
_id: 2,
score: 12,
total_score: 78 // Sum of current score and previous total_score
created_at: "2021-04-03"
},
{
_id: 3,
score: 7,
total_score: 85 // Sum of current score and previous total_score
created_at: "2021-04-06"
}
任何见解表示赞赏。
解决方案
您可以尝试聚合查询,
$lookup
使用管道并匹配大于查询依据_id
以选择上一条记录$group
通过 null 并获得总和score
$arrayElemAt
从查找结果中获取第一个元素$ifNull
检查结果是否为 null 然后返回 0 否则返回当前值$add
score
从查找中获取总分并返回分数
db.collection.aggregate([
{
$lookup: {
from: "collection",
let: { id: "$_id" },
pipeline: [
{ $match: { $expr: { $gt: ["$$id", "$_id"] } } },
{
$group: {
_id: null,
score: { $sum: "$score" }
}
}
],
as: "total_score"
}
},
{
$addFields: {
total_score: {
$add: [
"$score",
{
$ifNull: [
{ $arrayElemAt: ["$total_score.score", 0] },
0
]
}
]
}
}
}
])
推荐阅读
- visual-studio - Visual Studio 显示错误的 Windows SDK 版本
- azure - Azure 计费发票 URL 不可用
- javascript - 防止在 Web 应用程序的移动视图上提交表单时关闭键盘
- python-3.x - pymongo 获取关系对象查询问题
- flutter - 如何在颤动中绘制动态高度线?
- c# - 如何在 C# 中使用正则表达式从字符串中提取域名?
- flutter - 需要作为义务 - 颤振
- flutter - 使用类似 TabBar 的过滤器
- algorithm - 在 O(1) 中找到 AVL 树的中位数
- entity-framework-core - 如何获取 EF-Core MigrationSqlGenerator 中 Generate 函数生成的 SQL 命令?