Home > OS >  MongoDb convert to array a field in every subdocument
MongoDb convert to array a field in every subdocument

Time:01-14

I have a collection of students, each student has one or more addresses, each address has 1 phone number but now I need to change that to a list of phone numbers, therefore, an array.

I tried this, but the result is that it creates an array of phones and inside a new array with the phone, so double array for some reason:

db.students.updateMany(
  { "address.phone": { $exists: true } },
  [{ $set: { "address.phone": ["$address.phone"] } }]
)

Then I tried this, but the result is that it takes all phones from all addresses of the student and places them in the array of all the addresses, so if the student has 3 addresses with 1 phone each, all his addresses now have all 3 phone numbers.

db.students.updateMany(
  { "address.phone": { $exists: true } },
  [{ $set: { "address.phone": "$address.phone" } }]
)

I don't really understand how this work, how can I write something like "for each address make an array and insert the current value as element 0 of that array"?

Thanks for your help.

CodePudding user response:

db.students.update({
  "address.phone": {$exists: true}
},
[
  {
    $set: {
      "address": {
        $map: {
          input: "$address",                         //for each address in the array
          in: {
            $mergeObjects: [
              "$$this",                              //merge the whole address with modified phone field
              {
                phone: {
                  $cond: [
                    {$gt: ["$$this.phone",null]},    //if, phone is present in a address
                    ["$$this.phone"],                //make it an array
                    "$$REMOVE"                       //else, don't keep it
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])

Demo

  • Related