Objects, arrays and dates can be stored in a single document.

[Mongo Weekly] Update Documents using $set, $push and $addToSet

Hanjun Chen
2 min readNov 5, 2017

--

This week I have been practicing on the Applicants collection that we have been using (if you haven’t checked out my other articles using the same collection, check out the articles below:

Add a field to all documents

Let’s say we have a document as below:

And we want to add a Date type field called createDate to all the documents in the collection. We can use $set:

We set the multi attribute to true in the 3rd parameter, that way we can update all the documents (but, be careful please).

Add elements to an array

As we can see the framework field is an Object type, where the property key are programming language names, and the values are arrays with string values, which are, frameworks of that specific language (for example, the Swift attribute can have elements [“Server APIs” , “Kitura”] etc).

For the record above, we want to add an attribute called C++, and add 1 element to its array values using $addToSet:

And the second query used $push. They are similar but different:

Results

I like the calendar icon for Date-type fields

Please leave comments and suggestion below. Thank you for reading!

--

--

Hanjun Chen

Software developer with .Net, Node.js, AWS and marketing background.