How can I update an embedded document in a set or insert one if it doesn't exist in single query? Say I have a document like below. And 'records' is a set of embedded documents.
{
id: "1",
records: [
{userId:"5", userData: "..."},
{userId:"12", userData: "..."},
{userId:"27", userData: "..."}
]
}
I know how to insert or update 'records' in separate queries. But can I combine these queries so that it works similarly to MySQL's ON DUPLICATE KEY UPDATE? I want to avoid executing another query just to find out if an embedded document exists.
db.myCollection.update(
{id:"1", records.userId:"12"},
{records.$.userData:{"... new data ..."}}
);
db.myCollection.update(
{id:"1"},
{records:
{$push:
{userId: "33", userData: {"... new data ..."}}
}
}
);
Thanks