I have a dictionary that looks like this:
{
\"username\": \"SHAURYA\",
\"stocks\": [{
\"name\": \"WXYZ\",
\"count\": 2,
\"price\"
For new items
db.cmpe285.update({"username":username}, {"$push": {"stocks":{"name":stock_symbol,"count":allotment,"price":initial_share_price}}})
For updating existing items, assuming you are updating allotment. you need to make use positional operator($) with array value referenced in the query.
db.cmpe285.update({"username":username, "stocks.name":stock_symbol}, {"$set": {"stocks.$.count":allotment2}})
For upserting items, its a 2 step process. You'll first need run the query the same way you do for updating existing items as above and inspect the write result response from the above query and check the modified count. If the modified count is 0 means we need to upsert and then you'll just do it as in the case of adding new items.
db.cmpe285.update({"username":username, "stocks.name":stock_symbol}, {"$set": {"stocks.$.count":allotment2}})
Check the WriteResult, if nmodified equal to 0.
db.cmpe285.update({"username":username}, {"$push": {"stocks":{"name":stock_symbol,"count":allotment2,"price":initial_share_price}}})
If the nmodified equal to 1, upserting succeeded.
MongoDB is case-sensitive. Use "stocks" instead of "Stocks" in your push operation, and the subdocument will be correctly append to the array.