0

我试图弄清楚是否有一种方法可以使用诸如 $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 来做到这一点?

4

1 回答 1

0

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

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

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

于 2012-08-21T20:34:29.673 回答