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