如何在mongodb中的过滤器后仅输出/映射仅包含必需字段的数组? [英] How to output/ map an array with only the required fields after a filter in mongodb?

查看:149
本文介绍了如何在mongodb中的过滤器后仅输出/映射仅包含必需字段的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此数据:

{
"world": "Comic",
"characters": [
  {
    "character": "megaman",
    "type":"hero",
    "code":"123"
  },
  {
    "character": "dr willow",
    "type":"villain",
    "code":"1234"
  },
  {
    "character": "spiderman",
    "type":"hero",
    "code":"12345"
  },
  {
    "character": "venom",
    "type":"villain",
    "code":"123456"
  }
  
]
}

使用以下代码:

    db.collection.aggregate([
        {$addFields:{
            array_hero:{
                $filter:{
                    input: "$characters",
                    cond: {$eq:["$$this.type","hero"]}
                }
            },
            array_villain:{
                $filter:{
                    input: "$characters",
                    cond: {$eq:["$$this.type","villain"]}
                }
            },
        }}
    ])

输出为:

    {
    "array_hero": [
        {
        "character": "megaman",
        "type": "hero",
        "code": "123"
        },
        {
        "character": "spiderman",
        "type": "hero",
        "code": "12345"
        }
    ],
    "array_villain": [
        {
        "character": "dr willow",
        "type": "villain",
        "code": "1234"
        },
        {
        "character": "venom",
        "type": "villain",
        "code": "123456"
        }
    ]
    }

我想要这个输出,其中的数组仅使用characters.code构建,如下所示:

I want to have this output, where the arrays are only built with the characters.codelike this:

   {
    "array_hero": [
       "123","12345"
    ],
    "array_villain": [
       "1234","123456"
    ]
   }

我该怎么办?

推荐答案

您的聚合查询几乎就在那里.刚刚添加了 $map 阶段以选择必填字段/属性.

Your aggregation query is almost there. Just added a $map stage to pick the required fields/attributes.

db.collection.aggregate([
  {
    $addFields: {
      array_hero: {
        $filter: {
          input: "$characters",
          cond: {
            $eq: [
              "$$this.type",
              "hero"
            ]
          }
        }
      },
      array_villain: {
        $filter: {
          input: "$characters",
          cond: {
            $eq: [
              "$$this.type",
              "villain"
            ]
          }
        }
      },
      
    },
    
  },
  {
    $project: {
      array_hero: {
        $map: {
          input: "$array_hero",
          as: "hero",
          in: "$$hero.code"
        }
      },
      array_villain: {
        $map: {
          input: "$array_villain",
          as: "villain",
          in: "$$villain.code"
        }
      },
      
    }
  }
])

播放链接

这篇关于如何在mongodb中的过滤器后仅输出/映射仅包含必需字段的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆