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
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, weretool:xray
becomestool : [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.
update(
{},
[{"$set":
{"methods":
{"$map":
{"input": "$methods",
"in": {"$mergeObjects": ["$$this", {"tool": ["$$this.tool"]}]}}}}}],
{"multi": true})