If you are working with array properties in your Mongo documents you know that by using $push you can add a value to an existing array or create one and add the value to it like:
db.test.push({name:”TechnologicalAfrican”}, {$push:{partners:”Abou Kone”}})
But let’s say you have an array like
var partners = [“Coders4Africa”, “EtriLabs”, “IndexDot”]
and you want to update your array with those values, if you use $push again with the previous syntax, you will end up with a document that looks like:
{name:”TechnologicalAfrican”, partners:[“Abou Kone”, [“Coders4Africa”, “EtriLabs”, “IndexDot”] ]}
which is basically an embedded array as $push is for atomic values. Use $pushAll to add multiple values to an array like:
db.test.push({name:”TechnologicalAfrican”}, {$pushAll:{partners:[“Coders4Africa”, “EtriLabs”, “IndexDot”] }})
This will append the new values to the “partners” property in your document as you would expect.
Leave a Reply