PyMongo Update document with multiple records

前端 未结 2 585
自闭症患者
自闭症患者 2021-01-26 14:34

I have a dictionary that looks like this:

{
    \"username\": \"SHAURYA\",
    \"stocks\": [{
        \"name\": \"WXYZ\",
        \"count\": 2,
        \"price\"         


        
相关标签:
2条回答
  • 2021-01-26 14:48

    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.

    0 讨论(0)
  • 2021-01-26 14:51

    MongoDB is case-sensitive. Use "stocks" instead of "Stocks" in your push operation, and the subdocument will be correctly append to the array.

    0 讨论(0)
提交回复
热议问题