Mongo聚合将子文档数组转换为输出字节长度的字符串

时间:2020-03-19 16:34:48

标签: mongodb

我正在尝试获取匹配文档中field数组中每个子children的字节长度。我尝试了一些不利于我的咒语。

我正在使用mongodb 3.6

我有一个mongodb文档,

{
    "id": "string",
    "other-id": "string",
    "children": [
        {
            "field": "string"
        },
        { 
            "field": "string"
        },
        ...
    ]
}

我尝试过的事情:

  1. 通过children数组的长度获取大小(不是我想要的,但它可以工作)
[{
        "$match": {
            "id": {
                "$in": ["id1"]
            }
        }
    },
    {
        "$group": {
            "_id": "$otherId",

            "childSize": {

                "$sum": {
                    "$size": "$children"
                }
            }
        }
    }
]
  1. 使用concat将列表缩小为单个字符串(不知道我在做什么错,但这不起作用)。如果我可以执行此操作,则可以在$strLenBytes上使用concatenatedString来获取结果字节长度。
[
    {
        "$match": {
            "id": {
                "$in": ["id1"] // Perform the aggregation over a list of documents
            }
        }
    },
    {
        "$addFields": {
            "concatenatedString": {
                "$reduce": {
                    "input": "$children",
                    "initialValue": "",
                    "in": {
                        "$concat": ["$$value", "$$this.field"] 
                    }
                }
            }
        }

    }
]

问题:

  1. 获取field值并串联为单个字符串值。似乎这可能是目前对mongo聚合的限制?

解决方法:

  • 解决方法是将文档加载到python / js中并在那里进行计算,这对我来说足够了,但这并不理想。

有什么想法吗?

0 个答案:

没有答案
相关问题