Home > database >  how to change the field value of objects in array from string to array of string
how to change the field value of objects in array from string to array of string

Time:10-25

i have a document structure like this:

{
    "_id": "...",
    "shop": "pepe",
    "fruits": [
      {
        "name": "banana",
        "taste": "sweet",
      },
    ]
}

Now i want to change the type of fruits.taste to an array like this: "taste": ["sweet"]

So the result should be this:

{
    "_id": "...",
    "shop": "pepe",
    "fruits": [
      {
        "name": "banana",
        "taste": ["sweet"],
      },
    ]
}

i was trying to do that like this in a mongo playground query but that does not work:

db.getCollection('shops')
  .find()
  .forEach(function(document) {
   db.shops.update(
      { _id: document._id },
      { $set: { "document.fruits.$[].taste": [document.fruits.$.taste] } }
   );
})

How can i change in objects, which are in an array, a value from string to an array of string ?

Thanks for your help!

CodePudding user response:

Here's one way you could do it by using a pipeline in the update.

db.shops.update({
  "fruits.taste": {
    "$exists": true
  }
},
[
  {
    "$set": {
      "fruits": {
        "$map": {
          "input": "$fruits",
          "as": "fruit",
          "in": {
            "$mergeObjects": [
              "$$fruit",
              {"taste": ["$$fruit.taste"]}
            ]
          }
        }
      }
    }
  }
],
{"multi": true}
)

Try it on mongoplayground.net.

CodePudding user response:

Query

  • you need to refer to an existing field, and use $taste so you need a pipeline update
  • map on fruts, and put the taste value inside []

Playmongo

shops.update(
{},
[{"$set": 
   {"fruits": 
     {"$map": 
       {"input": "$fruits",
        "in": {"$mergeObjects": ["$$this", {"taste": ["$$this.taste"]}]}}}}}],
{"multi": true})
  • Related