I have collection with a document like this:
{
_id : "abcd",
name : "Tom",
myArray : [
{
field1 : "",
field2 : ""
}
]
},
{
_id : "efgh",
name : "Jerry"
}
I have a new object for myArray. I want to write a query to update only one document.
If the query matches the document with _id : "abcd", then push the new object in to myArray field:
{
_id : "abcd",
name : "Tom",
myArray : [
{
field1 : "",
field2 : ""
},
{
// new object
}
]
}
And if the query matches with _id : "efgh" create the field myArray with new object inside it:
{
_id : "efgh",
name : "Jerry"
myArray : [
{
// new object
}
]
}
How can I achieve this?
$pushan array to a document where it does not exist is that it just creates the array. Where there is an existing array the then new document is appended. So either you have not tried at all or there is still something missing from your question about what you really want to do.