条件更新:仅当值为None或“null”或密钥不存在时才更新

时间:2012-08-21 15:52:47

标签: python mongodb pymongo

我正在试图弄清楚是否有办法使用诸如$ set之类的条件来进行更高级的更新。这就是我在伪代码中要做的事情:

# new data to use in a possible update
newData = { 'emailAddress' : $usersEmailAddress,
            'keyA' : 'valueA', 
            'keyB' : None,
            'keyC' : '<null>' }

self.request.root.db.users.update(
                { 'emailAddress' : newData['emailAddress'] },
                { '$set': { 
                          "Here, loop through all newData keys/values and if 
                          notNull(newData[key]) == True and is different than the 
                          corresponding key/value in the user 
                          document (or if user document doesn't have that key) 
                          than update with newData key/value"
                          } }, upsert = False, safe = True )

# The result should be that if the value of keyA (and ONLY key A because the 
#  others are null) is different in the user document
#  than in newData, than the user document should be updated with the new value.



# function to catch any possible None value or equivalent string
def notNull(valueToCheck):
    if thingToCheck and thingToCheck != "null" and thingToCheck != 'nil' and thingToCheck != '<null>' and thingToCheck != '' and thingToCheck != ' ':
        return True
    else:
        return False

最有效的方法是什么?因为目前我不得不用find_one来拉整个文档,而且我被告知,这相当昂贵。有没有办法用$ set?

来做到这一点

1 个答案:

答案 0 :(得分:0)

不,MongoDB不支持此功能。正如您所说,您可以检索文档,在客户端代码中对其进行分析,并根据其内容发布更新,或者您可以发布一系列更新,如:

db.users.update({
    'emailAddress': newData['emailAddress'],
    '$or': [
        { 'keyA': { '$exists': false } },
        { 'keyA': None } ] }
    ]
}, {
    '$set': { 'keyA': newData['keyA'] }
})

前者将更有效,当然,因为它是单次提取和单次更新。但请考虑是否需要防止多个MongoDB客户端同时获取和更新同一文档。