嵌套字典中的值总和,不包括一些基于 MongoDB 数据库中其他键的值

Sum of the values in nested dicts excluding some based on other key in MongoDB database

我有一个 MongoDB 数据库,格式如下:

    {
    "_id": xxx,
    "timestamp": "1643649900000",
    "scores":
        [{
        "name": "APPL",
        "price": 80
        },
        {
        "name": "GOOGL",
        "price": 83,
        },
        {
        "name": "COMPI",
        "price": 76,
        },
        {
        "name": "and more names which also can change in the following documents",
        "price": 76,
        }]
    },
    {
    "_id": yyy,
    "time": "1644350400000",
    "scores":
        [{
        "name": "STCMP",
        "price": 33
        },
        {
        "name": "APPL",
        "price": 95,
        },
        {
        "name": "GOOGL",
        "price": 83,
        },
        {
        "name": "MINN",
        "price": 76,
        }]
    },

我需要每次对所有价格求和,但不包括(或从总和中减去)一些。

我的分数列表有大约 200 个听写,我想排除其中大约 5 个。 我只做了求和部分,但搜索了两天,以我有限的知识仍然无法排除。

toBeExcluded = ["APPL", "GOOGL"]
sums.aggregate([
            {
                "$unwind" : "$scores"
            },
            {
                "$group": {
                    "_id": "$time",
                    "total": {
                        "$sum": "$scores.price"
                    }
                }
            },
            {
                "$addFields":{
                    "timeAdj": {"$toInt": [{"$subtract":[{"$divide": ["$_id", 1000]}, 300]}]}
                }
            },
            {
                "$sort": {"timeAdj":1}
            }
            ]))

在您的 $sum:

中使用 $cond and check names to be excluded using $in

mongo playground

db.collection.aggregate([
  {
    "$unwind": "$scores"
  },
  {
    "$group": {
      "_id": "$time",
      "total": {
        "$sum": {
          "$cond": [
            {
              "$in": [
                "$scores.name",
                [
                  "APPL",
                  "GOOGL"
                ]
              ]
            },
            0,
            "$scores.price"
          ],
          
        }
      }
    }
  },
  
])