我想知道是否有可能在$sum函数中使用$match运算符进行聚合.

{   "$unwind": "$info.avatarInfoList" },
{   "$unwind": "$info.avatarInfoList.equipList" },
{   "$unwind": "$info.avatarInfoList.equipList.flat.reliquarySubstats" },
{
    "$project": {
        "name" : "$name",
        "character" : "$info.avatarInfoList.avatarId",
        "artifact" : "$info.avatarInfoList.equipList.itemId",
        "statValue" : {
            "$sum": [
                 {"$match" : { "$info.avatarInfoList.equipList.flat.reliquarySubstats.appendPropId" : "FIGHT_PROP_CRITICAL_HURT" } },
                 {"$multiply": [2, {"$match" : { "$info.avatarInfoList.equipList.flat.reliquarySubstats.appendPropId" : "FIGHT_PROP_CRITICAL" } }]}
            ]
        },
    }
},
{ "$sort": { "statValue": -1 }},
{ '$limit' : 30 }
]).to_list(length=None) 
print(data)

我希望能够在项目字段中使用$sum运算符的值,但我真的不知道正确的方法是什么.

样本输入(可能太长):

样本输出:

{name: hat, character: Slayer, artifact: 13, statValue : 25.6}

推荐答案

关于如何聚合数据,仍有一些模糊之处,但使用your link中的完整文档,这里有一种方法可以生成所需的输出.

N、 B.:"equipList"中的武器没有"reliquarySubstats",所以它们在输出中显示null中的"statValue".

db.collection.aggregate([
  {"$unwind": "$info.avatarInfoList"},
  {"$unwind": "$info.avatarInfoList.equipList"},
  {
    "$project": {
      "_id": 0,
      "name": 1,
      "character": "$info.avatarInfoList.avatarId",
      "artifact": "$info.avatarInfoList.equipList.itemId",
      "statValue": {
        "$reduce": {
          "input": "$info.avatarInfoList.equipList.flat.reliquarySubstats",
          "initialValue": 0,
          "in": {
            "$switch": {
              "branches": [
                {
                  "case": {"$eq": ["$$this.appendPropId", "FIGHT_PROP_CRITICAL"]},
                  "then": {
                    "$add": [
                      "$$value",
                      {"$multiply": [2, "$$this.statValue"]}
                    ]
                  }
                },
                {
                  "case": {"$eq": ["$$this.appendPropId", "FIGHT_PROP_CRITICAL_HURT"]},
                  "then": {"$add": ["$$value", "$$this.statValue"]}
                }
              ],
              "default": "$$value"
            }
          }
        }
      }
    }
  },
  {"$sort": {"statValue": -1}}
])

试试mongoplayground.net码.

Python相关问答推荐

从列表中获取n个元素,其中list [i][0]== value''

替换现有列名中的字符,而不创建新列

Pandas:填充行并删除重复项,但保留不同的值

计算空值

如何获取给定列中包含特定值的行号?

函数()参数';代码';必须是代码而不是字符串

某些值的数值幂和**之间的差异

将索引表转换为Numy数组

组颠倒大Pandas 数据帧

正则表达式反向查找

如何强制SqlalChemy指向与连接字符串的默认架构不同的架构

为什么Python多处理.Process()传递队列参数并且读取比函数传递队列参数和读取更快?

滑动子数组美容工作在IDE上,但不是在leetcode上

更改我的NN中的隐藏层数会导致错误

使用Numpy进行重写For循环矢量化

自由空间里的激光...以及我如何才能检测到Line以进行进一步计算?

Django按字段上的子字符串分组

基于时间间隔扩展Pandas DataFrame中的行,考虑可选中断

通过np.interp的辅助x轴:如何更改xlims

Python修饰器类型提示