我有一个数据的例子:
{
        "id": "2",
        "items":
            {
              "3" : { "blocks" : { "3" : { "txt" : 'xx' } } },
              "4" : { "blocks" : { "1" : { "txt" : 'yy'}, "2" : { "txt" : 'zz'} } }
            }
         }我想让它看起来像下面的示例数据。只需向items.3.block s.3.txt追加一个新值,同时保留其现有值:
 {
        "id": "2",
        "items":
            {
              "3" : { "blocks" : { "3" : { "txt" : 'xx, tt' } } },
              "4" : { "blocks" : { "1" : { "txt" : 'yy'}, "2" : { "txt" : 'zz'} } }
            }
         }我在下面跑,但没有任何区别。
dbx.test.update({"_id": ObjectId("5192264c02a03e374e67d7be")}, {'$addToSet': {'items.3.blocks.0.txt': 'tt'}}, )什么应该是正确的语法,任何帮助都是感谢的…问候
发布于 2013-05-15 00:13:16
我没有意识到这是一个mongodb|pymongo问题。
a = {
    "id": "2",
    "items": {
              "3" : { "blocks" : { "3" : { "txt" : 'xx' } } },
              "4" : { "blocks" : { "1" : { "txt" : 'yy'}, "2" : { "txt" : 'zz'} } }
            }
     }
a['items']['3']['blocks']['3']['txt'] += ', yy'关于如何修改dicts的简短回答:
a = {'moo' : 'cow', 'quack' : 'duck'}
a['moo'] = 'bull'
a['quack'] = 'duckling'
print(str(a))
if a['moo'] == 'bull':
    print 'Yes the bull says moo'如果您的数据是JSON字符串,您首先需要将其从JSON字符串转换为Python中的字典,方法是:
import json
a = json.loads(<your string goes here>)https://stackoverflow.com/questions/16547936
复制相似问题