首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套dicts中的值之和(不包括基于MongoDB数据库中其他键的值)

嵌套dicts中的值之和(不包括基于MongoDB数据库中其他键的值)
EN

Stack Overflow用户
提问于 2022-02-11 15:30:24
回答 1查看 63关注 0票数 1

我有一个具有以下格式的MongoDB数据库:

代码语言:javascript
复制
    {
    "_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条。我只做了总结部分,但经过两天的搜索仍然无法排除我有限的知识。

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-11 16:10:41

在您的$cond中使用$in并检查要排除的名称

蒙戈游乐场

代码语言:javascript
复制
db.collection.aggregate([
  {
    "$unwind": "$scores"
  },
  {
    "$group": {
      "_id": "$time",
      "total": {
        "$sum": {
          "$cond": [
            {
              "$in": [
                "$scores.name",
                [
                  "APPL",
                  "GOOGL"
                ]
              ]
            },
            0,
            "$scores.price"
          ],
          
        }
      }
    }
  },
  
])
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71082595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档