Python-MongoDB更新和删除不起作用

时间:2017-07-07 00:02:16

标签: python mongodb pymongo

有人可以告诉我为什么更新,删除和删除不起作用?不工作?这些只是从教程中汇总的代码。这是代码示例:

from pymongo import MongoClient
from pprint import pprint

client = MongoClient('localhost', 27017) 

collection_name = 'ursa_db'
db = client[collection_name]
print (db)

#Inserting Documents
posts = db.posts

post_data = {
    'title': 'MongoDB trial',
    'content': 'data',
    'author': 'Ursa'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))

posts_data = [
{
'title': 'Python and MongoDB',
'content': 'PyMongo is ok',
'author': 'Scott'
}, 
{
'title': 'Virtual Environments',
'content': 'Use virtual environments, ok',
'author': 'Scott'
}, {
'title': 'Learning Python',
'content': 'Learn Python',
'author': 'Bill'
}]
new_result = posts.insert_many([posts_data[0], posts_data[1], posts_data[2]])
print('Multiple posts: {0}'.format(new_result.inserted_ids))

#Finding Documents
bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)

scotts_posts = posts.find({'author': 'Scott'})
print(scotts_posts)

for post in scotts_posts:
    print(post)

#Caveat: error: not working 
db.ursa_db.update(
  { 'title': 'Virtual Environments', 'author': 'Scott' },
  {
    '$set': { 
        'author': 'To Be Determined'
    },
    #'$currentDate': { "lastModified": "true" }
  }
, upsert=False, multi=True
)

#Caveat: error: not working
try:
    criteria = 'Scott'
    db.ursa_db.delete_many({'author': criteria})
    print ('\nDeletion successful\n')
except (Exception, e):
    print (str(e))

print("=======================================")

cursor = posts.find({})
for document in cursor: 
    pprint(document)
print("=======================================")    

#Finding Documents
bills_post = posts.find_one({'author': 'To Be Determined'})
print(bills_post)   

scotts_posts = posts.find({'author': 'Scott'})
for post in scotts_posts:
    print(post)

更新和删除后,集合仍然相同。

0 个答案:

没有答案