PyMongo Update document with multiple records

别来无恙 提交于 2019-12-20 07:29:51

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/41112403/pymongo-update-document-with-multiple-records

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!