简体   繁体   English

PyMongo和Mongodb:使用update()

[英]PyMongo and Mongodb: using update()

I am trying to use pymongo to update an existing index: 我正在尝试使用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

I've been trying to follow documentation and examples I have seen on SO but none of them seem to be working for me. 我一直在努力遵循我在SO上看过的文档和示例,但似乎没有一个对我有用。 Anyone can explain what I'm doing wrong here? 任何人都可以解释我在这里做错了什么?

Thanks! 谢谢!

Use this (don't forget to add multi=True if you want to update all matches): 使用此功能(如果要更新所有匹配项,请不要忘记添加multi=True ):

db.tests.update({'active':True, 'name':'Blah'}, {'$set': {'active': False}}, multi=True)

Why your code isn't working: 为什么你的代码不起作用:

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,
    )

When you want to commit changes made to a retrieved doc, use collection.save instead of update : 如果要提交对检索到的doc所做的更改,请使用collection.save而不是update

test['active'] = False
db.tests.save(test)

Both of these worked for me: 这两个对我有用:

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)

Thanks very much traceur and JonnyHK! 非常感谢traceur和JonnyHK!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM