嵌套dict中的值之和,不包括MongoDB数据库中基于其他键的值



我有一个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并使用$in检查要排除的名称

蒙戈游乐场

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

}
}
}
},

])

相关内容

最新更新