To explain all the possible cases here, consider each case of the document:
If your document looks like this:
{ "_id": "efgh", "name": "Jerry" }
Then update this status:
db.collection.update( { "_id": "efgh" }, { "$push": { "myArray": { "field1": "abc", "field2": "def" } } )
Results in this:
{ "_id": "efgh", "name": "Jerry", "myArray": [ { "field1": "abc", "field2": "def" } ] }
So, the array is created and a new element is added.
If your document already has such an array:
{ "_id": "abcd", "name": "Tom", "myArray": [ { "field1": "", "field2": "" } ] }
And you basically make the same statement:
db.collection.update( { "_id": "abcd" }, { "$push": { "myArray": { "field1": "abc", "field2": "def" } } )
Then the contents of the new document are added to the existing array:
{ "_id": "abcd", "name": "Tom", "myArray": [ { "field1": "", "field2": "" }, { "field1": "abc", "field2": "def" } ] }
If your source document has a named field, but it is not an array, for example:
{ "_id": "efgh", "name": "Jerry", "myArray": 123 }
Then make sure that it is not an array by testing under the conditions of the query and instead of $set :
db.collection.update( { "_id": "efgh", "myArray.0": { "$exists": false } }, { "$set": { "myArray": [{ "field1": "abc", "field2": "def" }] } )
This will safely overwrite an element that is not an array (the dotted notation "myArray.0" means the first element of the array, which is incorrect) with a new array containing your content. The result is the same as the original:
{ "_id": "efgh", "name": "Jerry", "myArray": [ { "field1": "abc", "field2": "def" } ] }