问题描述
我有一本这样的字典:
{
"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.
如果我使用db.cmpe285.update({"username":username}, {"$push": {"stocks":{"name":stock_symbol,"count":allotment,"price":initial_share_price}}})
命令,则数据库不会更新.
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.
如果我使用db.cmpe285.update({"username":username}, {"$set": {"stocks":{"name":stock_symbol,"count":allotment,"price":initial_share_price}}})
命令,它将用新信息替换库存中的所有内容.
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?
推荐答案
用于新项目
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}})
要升级项目,这是一个两步过程.首先,您需要以与更新现有项目相同的方式运行查询,并检查上述查询的写入结果响应并检查修改后的计数.如果修改后的计数为0,则意味着我们需要上调,然后您就可以像添加新项一样进行操作.
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}})
检查 WriteResult ,如果nmodified等于0.
Check the WriteResult, if nmodified equal to 0.
db.cmpe285.update({"username":username}, {"$push": {"stocks":{"name":stock_symbol,"count":allotment2,"price":initial_share_price}}})
如果nmodified等于1,则上推成功.
If the nmodified equal to 1, upserting succeeded.
这篇关于PyMongo更新具有多个记录的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!