admin管理员组文章数量:1398832
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 badges1 Answer
Reset to default 2I 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"
}
]
本文标签: springMongoDB Rename field with derived Value of another fieldStack Overflow
版权声明:本文标题:spring - MongoDB Rename field with derived Value of another field - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744632891a2616647.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论