如何检查同一文档中6个值中的任意3个

2024-10-03 15:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python制作一款口袋妖怪游戏,我需要一些聚合方面的帮助,比如

# I have this at the moment.

# But I know that it isn't correct.
aggregations = [
    {
        "$match": {
            "$and": [
                {"$or": [{'hp': 28}, {'atk': 28}]},
                {"$or": [{'def': 28}, {'spatk': 28}]},
                {"$or": [{'spdef': 28}, {'speed': 28}]}
            ]
        }}]

# Database Structure

# Pokemon, Level, XP, SPDEF, SPATK, SPEED, HP, ATK, DEF.
"""
So I have some flags namely --trip <val>, --quad <val>

So if user do --trip 31, So it should match that in SPDEF, SPATK, SPEED, HP, ATK, DEF (ANY THREE).
"""

Tags: orsothatdefhavematchitval
1条回答
网友
1楼 · 发布于 2024-10-03 15:21:59

使用$project,如果值大于28,则可以存储在新变量中,并对每个属性执行此操作

然后用一个新的$project对所有新变量求和

然后只匹配大于或等于3的总数

[
{
    "$project": {
        "has_hp": {
            "$cond": {
                "if": {"$gte": ["$hp", 28]},
                "then": 1,
                "else": 0,
            }
        },
        "has_atk": {
            "$cond": {
                "if": {"$gte": ["$hp", 28]},
                "then": 1,
                "else": 0,
            }
        },
        "has_def": {
            "$cond": {
                "if": {"$gte": ["$hp", 28]},
                "then": 1,
                "else": 0,
            }
        },
        "has_spatk": {
            "$cond": {
                "if": {"$gte": ["$hp", 28]},
                "then": 1,
                "else": 0,
            }
        },
        "has_spdef": {
            "$cond": {
                "if": {"$gte": ["$hp", 28]},
                "then": 1,
                "else": 0,
            }
        },
        "has_speed": {
            "$cond": {
                "if": {"$gte": ["$hp", 28]},
                "then": 1,
                "else": 0,
            }
        }
    }
},
{
    "$project": {
        "total": { "$add": ["$has_hp", "$has_atk", "$has_def", "$has_spatk", "$has_spdef", "$has_speed"]}
    }
},
{
    "$match": {"total": {"$gte": 3}}
}
]

相关问题 更多 >