简体   繁体   English

在不重复的情况下将值添加到子文档中的数组(嵌套在主文档中)-MongoDB

[英]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: 总结一下,我想:

  1. Add a value to an array (without duplication), and the array is within a sub-document, that is within an array of a main document. 向数组添加一个值(不重复),该数组位于子文档内,即在主文档数组内。 (Document > Array > Subdoc > Array) (文档>数组>子文档>数组)
  2. The subdocument itself might not exist, so if not exist, the subdocument itself need to be added, ie UpSert 子文档本身可能不存在,因此,如果不存在,则需要添加子文档本身,即UpSert
  3. The command be the same for both action (ie adding of value to subdoc's array, and adding of subdoc) 这两个操作的命令是相同的(即,将值添加到子文档的数组,以及添加子文档)

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. 可以很好地做到嵌套的updateupsert而重复检查可能不会,因为没有直接的方法来检查项目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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM