Home > Back-end >  MongoDB how to change field type in array from string to array and keep original value
MongoDB how to change field type in array from string to array and keep original value

Time:12-02

Image of original document

I have db "test" with collection "testing". In that collection I have document with array called "methods" which contains object 0(and maybe lot more objects 1,2,3,4...). Inside those objects I have string field "tool" with tool "xray". I want that string field "tool" to be array of tools. I found command to change tool field to array with:

db.testing.update(
  {},
  [{ $set: { "methods.tool": ["$methods.tool"] } }],
  { multi: true }
)

This works but it creates one extra array "0:Array" and I dont want that

Outcome

I want the end result look like this: end result

CodePudding user response:

Query

  • $map to update all document members of methods
  • $$this is the current member each time
  • $mergeObjects is used to add the updated field, were tool:xray becomes tool : [xray]

*paths that the field is part of array, they are arrays also, "$methods.tool" is an array of all the tools in all methods.

Test code here

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