[英]Adding value to array in sub-document (nested within main doc) without duplication - MongoDB
it is quite complicated with the nested documents, but please let me know if you all has any solutions, thanks. 嵌套文档非常复杂,但是请告诉我是否有任何解决方案,谢谢。
To summarize, I would like to: 总结一下,我想:
I have tried the following, but it doesn't work: 我已经尝试了以下方法,但是不起作用:
key = {'username':'user1'}
update1 = {
'$addToSet':{'clients':{
'$set':{'fname':'Jessica'},
'$set':{'lname':'Royce'},
'$addToSet':{'cars':'Toyota'}
}
}
}
#the document with 'Jessica' and 'Royce' does not exist in clients array, so a new document should be created
update2 = {
'$addToSet':{'clients':{
'$set':{'fname':'Jessica'},
'$set':{'lname':'Royce'},
'$addToSet':{'cars':'Honda'}
}
}
}
#now that the document with 'Jessica' and 'Royce' already exist in clients array, only the value of 'Honda' should be added to the cars array
mongo_collection.update(key, update1 , upsert=True)
mongo_collection.update(key, update2 , upsert=True)
error message: $set is not valid for storage 错误消息:$ set对于存储无效
My intended outcome: 我的预期结果:
Before: 之前:
{
'username':'user1',
'clients':[
{'fname':'John',
'lname':'Baker',
'cars':['Merc','Ferrari']}
]
}
1st After: 第1次之后:
{
'username':'user1',
'clients':[
{'fname':'John',
'lname':'Baker',
'cars':['Merc','Ferrari']},
{'fname':'Jessica',
'lname':'Royce',
'cars':['Toyota']}
]
}
2nd After: 第二个之后:
{
'username':'user1',
'clients':[
{'fname':'John',
'lname':'Baker',
'cars':['Merc','Ferrari']},
{'fname':'Jessica',
'lname':'Royce',
'cars':['Toyota','Honda']}
]
}
My understanding says you won't be able to completely achieve intended solution directly. 我的理解是,您将无法直接完全实现预期的解决方案。 You can very well do nested
update
or upsert
but duplication check probably not, as there is no direct way to check item contains
in a array document. 可以很好地做到嵌套的
update
或upsert
而重复检查可能不会,因为没有直接的方法来检查项目contains
一个数组文件内。
For upsert
operation you can refer mongodb update operation doc or bulk operation. 对于
upsert
操作,您可以参考mongodb更新操作文档或批量操作。 And for duplication probably you need to have separate logic to identify. 对于重复,您可能需要使用单独的逻辑来识别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.