Difference between $set and $push

from the video if my understanding is correct $push I can add an element to array field. with $set we can set new value to specified field.

In the video for $set if you give a field that does not exist the database still creates the field and adds value. will $push do the same if non-existent field name is given? if it does the same then what is the difference between $set and $push in this scenario?

Thank you in advance for clarification.
Siva

It is always best to refer to the documentation:


and

In particular for $push, you will find the note

If the field is not an array, the operation will fail.

For $set, you are able to set a specific element in the array. For $push it will always be at the end.

For $set, using the array dot notation might cause unexpected result when the given element does not exists. Because $set will not create an array field but an object field. For example, if you do

{ $set : { "MyArray.3" : "MyValue" } }

and MyArray does not exist you will end up with

{
  "MyArray" : { "3" : "MyValue" }
}

However if you do the same and “MyArray” exists as an array like in

{
  "MyArray" : [ "ExistingValue" ]
}

and you do the same operation as before you will end up with

{
  "MyArray" : [ "ExistingValue" , null , null , "MyValue" ]
}

Please note that I discovered some of the above special behavior while writing this post, so more might exist.

3 Likes

Thank You steevej-1495