首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于文档转换的类型

基于文档转换的类型
EN

Stack Overflow用户
提问于 2019-10-04 01:39:31
回答 1查看 41关注 0票数 2

假设我有一个mongodb文档

代码语言:javascript
运行
复制
{
  "id" : 1,
  "types" : ["online" ,"offline"],
  "applications" : [ ["online", "online"], ["offline"] ]
}

我想变身为

代码语言:javascript
运行
复制
{
"id" : 1,
"types" : [
        {
          "type" : "online",
          "count" : 2,
          "applications" : [ "online", "online"]
        },
        {
          "type" : "offline",
          "count" : 1,
          "applications" : [ "offline" ]
        }
    ]
}

在这里,类型和应用程序数组可以是任何大小。

EN

Stack Overflow用户

回答已采纳

发布于 2019-10-04 10:00:45

您可以通过两个步骤完成此操作,首先使用$map$filtertypeapplications匹配,然后运行$reduce以获取count

代码语言:javascript
运行
复制
db.collection.aggregate([
    {
        $project: {
            id: 1,
            types: {
                $map: {
                    input: "$types",
                    as: "type",
                    in: {
                        type: "$$type",
                        applications: {
                            $filter: {
                                input: "$applications",
                                as: "application",
                                cond: { 
                                    $allElementsTrue: {
                                        $map: { input: "$$application", in: { $eq: [ "$$this", "$$type" ] } }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    {
        $addFields: {
            types: {
                $map: {
                    input: "$types",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            { 
                                count: { 
                                    $reduce: { 
                                        input: "$$this.applications", 
                                        initialValue: 0, 
                                        in: { $add: [ "$$value", { $size: "$$this" }  ] } 
                                    }
                                } 
                            }
                        ]
                    }
                }
            }
        }
    }
])

您可以决定在构建筛选条件时使用$allElementsTrue$anyElementTrue哪个更好。

Mongo Playground

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58224308

复制
相关文章

相似问题

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