【问题标题】:Adding value to array in sub-document (nested within main doc) without duplication - MongoDB在不重复的情况下向子文档中的数组(嵌套在主文档中)添加值 - MongoDB
【发布时间】:2015-06-04 07:08:13
【问题描述】:

嵌套文档很复杂,但是如果大家有任何解决方案,请告诉我,谢谢。

总而言之,我想:

  1. 向数组添加一个值(不重复),并且该数组在子文档内,即在主文档的数组内。 (文档 > 数组 > 子文档 > 数组)
  2. 子文档本身可能不存在,如果不存在,需要添加子文档本身,即UpSert
  3. 两个动作的命令相同(即向子文档的数组添加值,以及添加子文档)

我尝试了以下方法,但它不起作用:

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)

错误信息:$set 对存储无效

我的预期结果:

之前:

{
   'username':'user1',
   'clients':[
   {'fname':'John',
    'lname':'Baker',
    'cars':['Merc','Ferrari']}
   ]
}

第一次之后:

{
   'username':'user1',
   'clients':[
   {'fname':'John',
    'lname':'Baker',
    'cars':['Merc','Ferrari']},
   {'fname':'Jessica',
    'lname':'Royce',
    'cars':['Toyota']}
   ]
}

第二次之后:

{
   'username':'user1',
   'clients':[
   {'fname':'John',
    'lname':'Baker',
    'cars':['Merc','Ferrari']},
   {'fname':'Jessica',
    'lname':'Royce',
    'cars':['Toyota','Honda']}
   ]
}

【问题讨论】:

    标签: python arrays mongodb nested pymongo


    【解决方案1】:

    我的理解是,您将无法直接完全实现预期的解决方案。您可以很好地进行嵌套updateupsert,但可能不会进行重复检查,因为没有直接的方法来检查数组文档中的项目contains

    upsert操作可以参考mongodb更新操作doc或者批量操作。对于重复,您可能需要有单独的逻辑来识别。

    【讨论】:

    • 我明白了...那么首先检查数组是否包含文档,如果没有,则添加文档,如果是,我需要再次检查是否subdoc 中的数组具有值。不确定是否有其他人遇到过这个问题,并且有更有效的方法来处理这个问题?
    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 2014-03-30
    • 2018-10-20
    • 1970-01-01
    • 2021-05-01
    • 2018-03-09
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多