skip to Main Content

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!

2

Answers


  1. 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})
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search