Python 使用PyMongo和MongoDB在同一更新中设置和设置addToSet
在MongoDb中,除了已经用addToSet等更新的字段外,是否可以对所有内容执行更新 我将信息存储在用户更新的python字典中。然后我想使用这个字典来更新MongoDb中的条目。其中一个字段是数组,如果没有,我想插入字典值。其他一切都可以替换。我的问题是在整个字典中使用set将数组替换为单个值。为了说明这个问题: 我编了一本字典Python 使用PyMongo和MongoDB在同一更新中设置和设置addToSet,python,mongodb,dictionary,pymongo,Python,Mongodb,Dictionary,Pymongo,在MongoDb中,除了已经用addToSet等更新的字段外,是否可以对所有内容执行更新 我将信息存储在用户更新的python字典中。然后我想使用这个字典来更新MongoDb中的条目。其中一个字段是数组,如果没有,我想插入字典值。其他一切都可以替换。我的问题是在整个字典中使用set将数组替换为单个值。为了说明这个问题: 我编了一本字典 thing = {} thing['name'] = 'fruit' thing['color'] = 'green' thing['types'] = ['ap
thing = {}
thing['name'] = 'fruit'
thing['color'] = 'green'
thing['types'] = ['apple', 'pear', 'kiwi']
我插入:
c_users.insert_one(thing)
用户标记要更新的某些字段
thing2 = {}
thing2['name'] = 'fruit'
thing2['color'] = 'darkgreen'
thing2['types'] = 'mango'
然后我尝试更新数据库
c_users.update({'name':thing2['name']},{'addToSet':{'types':thing2['types']},$set':{'color':thing2})
有可能使这种方法起作用吗?如果没有,还有其他方法可以实现相同的最终结果,例如使用变量代替thing2['types'],但最好将所有值保留在字典中。您可以从更新文档中弹出'types'值:
>>> c_users.find_one()
{u'color': u'green', u'_id': ObjectId('553fddc967d5bd0b07022477'), u'name': u'fruit', u'types': [u'apple', u'pear', u'kiwi']}
>>> thing2 = {'name': 'fruit', 'color': 'darkgreen', 'types': 'mango'}
>>> c_users.update({'name': thing2['name']}, {'$addToSet': {'types': thing2.pop('types')}, '$set': thing2})
{u'nModified': 1, u'ok': 1, u'n': 1, 'updatedExisting': True, u'electionId': ObjectId('553fc845f09926d0bb959eb7'), u'lastOp': Timestamp(1430249053, 1)}
>>> c_users.find_one()
{u'color': u'darkgreen', u'_id': ObjectId('553fddc967d5bd0b07022477'), u'name': u'fruit', u'types': [u'apple', u'pear', u'kiwi', u'mango']}