Update an array property in MongoDB with multiple values

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.

Advertisement

2 responses to “Update an array property in MongoDB with multiple values”

  1. Pretty cool! Are you using Mongo in production or are you testing it? I have a project I would like to use Mongo for. Do you have any recommended resources for learning it?

    1. Using it in production. It is actually a cool concept, if you are used to Javascript and manipulating JSON it will make sense to you. As far as learning it really, I get most of my info from the mongodb.org documentation, the command set is pretty limited which makes it quite easy to learn.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: