mongodbmongoosemongo-shellmongodb-update

How to add a new field with the reference field through Mongo shell


I have an address field value inside basicDetails. I want that value to bring to the root field by adding a new field named address, so I am trying this way to add a new field address in all the documents. But the issue is the value is unable to update. I think I am wrong in syntax for referencing the value properly. Please help me. Thanks in advance.

Updation Query:

db.businesslistings.updateMany({}, 
  {$set: {"address": '$attributes[0].basicDetails[1].valueString'}})

Result:

address: "$attributes[0].basicDetails[1].valueString"


Solution

  • The simple update query cannot do complex queries such as getting the field value. You need the update query with aggregation pipeline.

    The dot notation (path) doesn't work, you need the query as below:

    From inner to outer

    1. Get the first element of the attributes array.

    2. Get the basicDetails field.

    3. Get the second element of the basicDetails array.

    4. Get the valueString field.

    db.businesslistings.updateMany({},
    [
      {
        $set: {
          "address": {
            $getField: {
              input: {
                $arrayElemAt: [
                  {
                    $getField: {
                      input: {
                        $arrayElemAt: [
                          "$attributes",
                          0
                        ]
                      },
                      field: "basicDetails"
                    }
                  },
                  1
                ]
              },
              field: "valueString"
            }
          }
        }
      }
    ])
    

    Demo @ Mongo Playground