GreenAsJade GreenAsJade - 27 days ago 6
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 "
update
" 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
item.b
of the document with
item.a===1
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
b
above)

This could be

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


or

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

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

2)$addToSet:

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