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.

Published by Abou Kone

I am a front end architect with 10+ years of experience in web development. The best part of the process for me is converting ideas into code and solving the technical problems that come along. Alongside providing technical leadership and architectural support to projects spanning multiple industries, I am also experienced in leading discussions with designers, developers, and business stakeholders helping to guide teams in turning complex business workflows or data into easy-to-use web and mobile interfaces. I believe in delivering high quality products and am constantly looking into improving the process and tools use to achieve this goal.

2 thoughts on “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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: