Tuesday, May 21st

Last update09:35:45 PM GMT

Update an array property in MongoDB with multiple values

Rate this item
(0 votes)

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.

Contact us

  • Add: 554 N Frederick Avenue Suite 216,
    Gaithersburg, MD 20877 USA
  • Tel: (888) 418-1146
You are here: Blog Update an array property in MongoDB with multiple values