'How to update exists value (type: string) to array of ojbect and object in mongoDB?
I have following documents:
[
{
"_id": "6245131fdbcda3639d75c951",
"username": "joy",
"description": "description english",
"product_code_origin": "aaaa-a",
"product_code_filter": "aaaaa"
},
{
"_id": "6245131fdbcda3639d75c952",
"username": "joy2",
"description": "description 222",
"product_code_origin": "bbbb-b",
"product_code_filter": "bbbbb"
}
]
description will be object of string.
description: string => description: {description_en: exists string value}
product_code_origin and product_code_filter will be array of object.
product_code_origin: string, product_code_filter: string => [{product_code_origin: exists string value, product_code_filter: exists string value}]
the updated document would look like
[
{
"_id": "6245131fdbcda3639d75c951",
"username": "joy",
"description": {"description_en": "description english", "description_ko":""},
"product_code": [
{
"product_code_origin": "aaaa-a",
"product_code_filter": "aaaaa"
},
]
},
{
"_id": "6245131fdbcda3639d75c952",
"username": "joy2",
"description": {"description_en": "description 222", "description_ko":""}
"product_code": [
{
"product_code_origin": "bbbb-b",
"product_code_filter": "bbbbb"
}
]
}
]
Solution 1:[1]
Use update-documents-with-aggregation-pipeline
db.collection.update({},
[
{
$set: {
description: {
description_en: "$description",
description_ko: ""
},
product_code: [
{
product_code_origin: "$product_code_origin",
product_code_filter: "$product_code_filter"
}
]
}
},
{
$unset: [
"product_code_origin",
"product_code_filter"
]
}
],
{
multi: true
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | YuTing |