【问题标题】:addToSet and set in same update using PyMongo and MongoDBaddToSet 并使用 PyMongo 和 MongoDB 在同一更新中设置
【发布时间】:2015-07-07 15:30:50
【问题描述】:

在 MongoDb 中,是否可以对除已更新的字段(例如使用 addToSet)之外的所有内容执行更新?

我将信息存储在用户更新的 python 字典中。然后我想使用这本字典来更新 MongoDb 中的条目。其中一个字段是一个数组,如果字典值不存在,我想插入它。其他的都可以换。我遇到的问题是,将 set 与整个字典一起使用会用单个值替换数组。为了说明问题:

我创建了一个字典

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'] 但最好将所有值保留在字典中。

【问题讨论】:

    标签: python mongodb dictionary pymongo


    【解决方案1】:

    您可以从更新文档中弹出“类型”值:

    >>> 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']}
    

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 2020-08-16
      • 2012-04-12
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2020-08-23
      • 2021-07-04
      • 2017-04-08
      相关资源
      最近更新 更多