Home > OS >  how to update exists value (type: string) to array of ojbect and object in mongoDB?
how to update exists value (type: string) to array of ojbect and object in mongoDB?

Time:05-05

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"
      }
     ]
  }
]

I have following documents:

[
  {
    "_id": "6245131fdbcda3639d75c951",
    "product_code": {
      "product_code_filter": "aaaaa",
      "product_code_origin": "aaaa-a"
    },
    "username": "joy"
  },
  {
    "_id": "6245131fdbcda3639d75c952",
    "product_code": {
      "product_code_filter": "bbbbb",
      "product_code_origin": "bbbb-b"
    },
    "username": "joy2"
  }
]

exists object => [{product_code_origin: exists value, product_code_filter: exists value}]

the updated document would look like

[
  {
    "_id": "6245131fdbcda3639d75c951",
    "username": "joy",
    "product_code": [
       {
        "product_code_origin": "aaaa-a",
        "product_code_filter": "aaaaa"
       },
     ]
  },
  {
    "_id": "6245131fdbcda3639d75c952",
    "username": "joy2",
    "product_code": [
      {
        "product_code_origin": "bbbb-b",
        "product_code_filter": "bbbbb"
      }
     ]
  }
]

CodePudding user response:

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
})

mongoplayground

  • Related