Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB – Update a field based on another field within the same doc in the array

I have a collection of data like this:

{
    "items": [
      {
        "product": {
          "name": "prod1",
          "price": {
            "pledge": 1,
            "cost": 19
          }
        }
      },
      {
        "product": {
          "name": "prod2",
          "price": {
            "pledge": 2,
            "cost": 10
          }
        }
      }
    ]
  }

I want to update the whole collection have them like this:

{
    "items": [
      {
        "product": {
          "name": "prod1",
          "price": {
            "pledge": 1,
            "deposit": 1,
            "cost": 19
          }
        }
      },
      {
        "product": {
          "name": "prod2",
          "price": {
            "pledge": 2,
            "deposit": 2,
            "cost": 10
          }
        }
      }
    ]
  }

For each price in the items, I want to add a new field named deposit with the value of pledge in the same element.
How can I do it in an optimized way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should need the update query with aggregation pipeline to reference the field.

  1. $map – Iterate the elements in the items array

1.1. $mergeObjects – Merge the current iterated object with the document with price field.

1.1.1. $mergeObjects – Merge the product.price object with the document with deposit field referencing the product.price.pledge value.

db.collection.update({},
[
  {
    $set: {
      items: {
        $map: {
          input: "$items",
          in: {
            product: {
              $mergeObjects: [
                "$$this.product",
                {
                  "price": {
                    $mergeObjects: [
                      "$$this.product.price",
                      {
                        deposit: "$$this.product.price.pledge"
                      }
                    ]
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading