我有一个数据的例子:
{
"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>)发布于 2013-05-15 00:21:25
您需要使用'$push'而不是'$addToSet'
dbx.test.update({"_id": ObjectId("5192264c02a03e374e67d7be")}, {'$push': {'items.3.blocks.0.txt': 'tt'}}, )发布于 2013-05-15 22:01:27
很简单,因为将与$addToSet一起工作需要数组中的数据,但数据在{"key":"value"}中,但您有{ "blocks" : { "1" : { "txt" : 'yy'}, "2" : { "txt" : 'zz'} } },建议在数组中工作,例如
"items":
[
{ "algo" : { "blocks" : { "txt" : ['xx']} } } ,
{ "algoo" : { "blocks" : { "txt" : ['yy','zz']} } }
]
db.foo.update({"_id":1,"items.algo.blocks.txt":'xx'},{$addToSet:{"items.$.algo.blocks.txt":'tt'}});并且在字段name中不使用数字。
{
"_id" : 1,
"items" : [
{
"algo" : {
"blocks" : {
"txt" : [
"xx",
"tt"
]
}
}
},
{
"algoo" : {
"blocks" : {
"txt" : [
"yy",
"zz"
]
}
}
}
]
}https://stackoverflow.com/questions/16547936
复制相似问题