gpt4 book ai didi

mongodb - 当我创建一个 $group 时,如何返回所有对象中存在的属性的总和?

转载 作者:行者123 更新时间:2023-12-04 09:15:12 25 4
gpt4 key购买 nike

我有一个具有以下结构的数据库:

[
{
"provider": "provider 1",
"debts": [
{
"debt": 500,
"paid": true
},
{
"debt": 900,
"paid": false
},
{
"debt": 600,
"paid": false
}
]
},
{
"provider": "provider 2",
"debts": [
{
"debt": 500,
"paid": false
}
]
}
]
我希望每个对象都存储在 total 中字段 debt 的总和 debts 中包含的字段数组 ( debts.debt ) 仅当 paid属性是假的。 (在我的真实代码中,它在这里运行良好)。
db.collection.aggregate(
[
{
$unwind: "$debts",
},
{
$group: {
_id: "$_id",

total: {
$sum: {
$cond: [{ $eq: ["$debts.paid", false] }, "debts.debt", 0],
},
},
},
}
]
我怎样才能得到 total 的总和满足上述条件的所有对象中包含的属性?
{
"debts_providers": [
{
"_id": "5f29af0a17196c1624f7dd88",
"total": 1500
},
{
"_id": "5f29af0a17196c1624f7dd89",
"total": 500
}
],
"sum_total_objects": 2000 /*900+600+500*/
}

最佳答案

你在正确的轨道上,只需要用 debt_providers 替换 root ,

  • 你错过了 $第一组$cond then部分,应该是$debts.debt
  • 第二个$group这是必需的,
  • 创建新字段 debt_providers并推送 $$ROOT因为文件是独立展开的,但我们需要在debt_providers中设置在一起
  • 创建新字段 sum_total_objects$sum所有总值

  • db.collection.aggregate([
    {
    $unwind: "$debts"
    },
    {
    $group: {
    _id: "$_id",
    total: {
    $sum: {
    $cond: [
    { $eq: ["$debts.paid", false] },
    "$debts.debt", // corrected debts.debt to $debts.debt
    0
    ]
    }
    }
    }
    },
    // added here
    {
    $group: {
    _id: null,
    debt_providers: { $push: "$$ROOT" },
    sum_total_objects: { $sum: "$total" }
    }
    }
    ])
    游乐场: https://mongoplayground.net/p/esRanLrIB2o

    关于mongodb - 当我创建一个 $group 时,如何返回所有对象中存在的属性的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63256110/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com