GreenAsJade GreenAsJade - 11 months ago 66
Node.js Question

How to push a new element into an array inside a mongo doc using `update`?

The docs for nodejs mongodb driver's

function say that the second argument is an "
" document, but don't describe what one of those is.

They show an example of how to use this to set a root node value in a document:

var r = yield col.updateOne({a:1}, {$set: {b: 1}});

This sets the
of the document with
to 1.

... but I can't extrapolate from here to see how to add an element to an array that is a leaf (not at the root of the item like

This could be

col.updateOne({a:1}, {$push: {sub_node: {the_list: 1}}});


col.updateOne({a:1}, {sub_Node: {this_list: {$push: 1}});

... what's the actual way?

And (side question) where is this documented? How do we know how to do this?

Answer Source

You can use two operators 1) $push

col.updateOne({a:1}, {$push: {sub_node: {the_list: 1}}})

This will push the the_list variable inside a sub_node object array object


col.updateOne({a:1}, {$addToSet: {sub_node: {the_list: 1}}})

This will also do the same thing as $push but it will avoid duplicate entry inside sub_node array You can see mongodb documentation