I have a dictionary that looks like this:
{
"username": "SHAURYA",
"stocks": [{
"name": "WXYZ",
"count": 2,
"price": 100
}, {
"name": "GOOG",
"count": 3,
"price": 300
}, {
"name": "QQV",
"count": 5,
"price": 300
}, {
"name": "AAPL",
"count": 6,
"price": 300
}, {
"name": "SN",
"count": 4,
"price": 300
}]
}
I need to be able to update individual stocks as well as add new stocks to this.
If i use the db.cmpe285.update({"username":username}, {"$push": {"stocks":{"name":stock_symbol,"count":allotment,"price":initial_share_price}}})
command, the database does not get updated.
If i use the db.cmpe285.update({"username":username}, {"$set": {"stocks":{"name":stock_symbol,"count":allotment,"price":initial_share_price}}})
command, it replaces everything inside of stocks with the new information.
Is there any way I can update the existing records or even add a new record to this?
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.