最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

spring - MongoDB Rename field with derived Value of another field - Stack Overflow

programmeradmin0浏览0评论

I have a collection like -

[  {
    'k': 'Troubleshooting',
    'hour': '2024-10-10T16',
    'v': [ 'WebPage, Login' ]
  },
  {
    'k': 'TroubleshootingMe',
    'hour': '2024-10-07T01',
    'v': [ 'Accounts, etc' ]
  }
]

I wish to aggregate pipeline that results me documents like below -

[  {
    'hour': '2024-10-10T16',
    'Troubleshooting': [ 'WebPage, Login' ]
  },
  {
    'hour': '2024-10-07T01',
    'TroubleshootingMe': [ 'Accounts, etc' ]
  }
]

I know that I can use replaceroot Like below -

{
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [
          [
            {
              k: "$k",
              v: "$v"
            }
          ]
        ]
      }
    }
  }

But, that can be done only when I have 2 fields k & v. Is there a way I can select third hour field as well ...?

I have a collection like -

[  {
    'k': 'Troubleshooting',
    'hour': '2024-10-10T16',
    'v': [ 'WebPage, Login' ]
  },
  {
    'k': 'TroubleshootingMe',
    'hour': '2024-10-07T01',
    'v': [ 'Accounts, etc' ]
  }
]

I wish to aggregate pipeline that results me documents like below -

[  {
    'hour': '2024-10-10T16',
    'Troubleshooting': [ 'WebPage, Login' ]
  },
  {
    'hour': '2024-10-07T01',
    'TroubleshootingMe': [ 'Accounts, etc' ]
  }
]

I know that I can use replaceroot Like below -

{
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [
          [
            {
              k: "$k",
              v: "$v"
            }
          ]
        ]
      }
    }
  }

But, that can be done only when I have 2 fields k & v. Is there a way I can select third hour field as well ...?

Share Improve this question asked Mar 14 at 20:57 dinesh028dinesh028 2,2195 gold badges32 silver badges48 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

I think you're looking for the $mergeObjects operator. You can see a general reference for using that operator in conjunction with $replaceRoot/$replaceWith here in the documentation.

In your situation the pipeline would look something like:

db.collection.aggregate([
  {
    $replaceWith: {
      $mergeObjects: [
        {
          hour: "$hour"
        },
        {
          "$arrayToObject": [
            [
              {
                k: "$k",
                v: "$v"
              }
            ]
          ]
        }
      ]
    }
  }
])

Mongoplayground here. Output:

[
  {
    "Troubleshooting": [
      "WebPage, Login"
    ],
    "hour": "2024-10-10T16"
  },
  {
    "TroubleshootingMe": [
      "Accounts, etc"
    ],
    "hour": "2024-10-07T01"
  }
]
发布评论

评论列表(0)

  1. 暂无评论