我正在尝试使用 pymongo 更新现有索引:
#!/usr/bin/env python
import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.alfmonitor
tests = db.tests
post = {
'name' : 'Blah',
'active' : True,
'url' : 'http://www.google.com',
}
tests.insert(post)
tests_list = db.tests.find({'active':True, 'name':'Blah'})
for test in tests_list:
test['active'] = False
test.update(
test,
)
print '===================================================='
for test in db.tests.find():
print test #<- when I print out these, active=True is still showing up
我一直在尝试遵循我在 SO 上看到的文档和示例,但它们似乎都不适合我。任何人都可以解释我在这里做错了什么?
谢谢!
使用这个(如果你想更新所有匹配项,不要忘记添加multi=True
):
db.tests.update({'active':True, 'name':'Blah'}, {'$set': {'active': False}}, multi=True)
为什么你的代码不起作用:
for test in tests_list:
# test is of a dict type
test['active'] = False
# You are calling the method of dict type
# that adds all values from dictionary test to dictionary test,
# so nothing goes to database
test.update(
test,
)
当您要提交对检索到的文档所做的更改时,请使用collection.save
而不是update
:
test['active'] = False
db.tests.save(test)
这两个都对我有用:
db.tests.update(
{'active':True, 'name':'Blah'},
{
'$set': {'active': False}
},
multi=True
)
tests_list = db.tests.find({'active':True, 'name':'Blah'})
for test in tests_list:
test['active'] = False
db.tests.save(test)
非常感谢追踪者和JonnyHK!