mongodb中的update()返回什么
在为MongoDB的API编写Python脚本时……
我们有……
new_posts = [{ 'name': 'A', 'age': 17, 'marks': 97, 'school': 'School1' },
{ 'name': 'B', 'age': 18, 'marks': 95, 'school': 'School2' },
{ 'name': 'C', 'age': 19, 'marks': 97, 'school': 'School2' }]
db.posts.insert( new_posts )
我们创建索引的方法如下……
db.posts.create_index([('name',1),('school',1)],unique=True)
现在我们进行两个操作……
db.posts.update({ 'name':'A', 'age': 17, 'school': 'School3' },
{ 'name':'D', 'age': 17, 'marks': 70, 'school': 'School1' },
upsert=True )
db.posts.update({ 'name':'A', 'age': 17, 'school': 'School1' },
{ 'name':'A', 'age': 17, 'marks': 60, 'school': 'School1' },
upsert=True )
这里的update()返回了什么?我们怎么知道文档是被插入到数据库中,还是更新了已有的文档呢?
我们能否做一些类似于……
post1 = db.posts.update({ 'name':'A', 'age': 17, 'school': 'School3' },
{ 'name':'D', 'age': 17, 'marks': 70, 'school': 'School1' },
upsert=True )
post2 = db.posts.update({ 'name':'A', 'age': 17, 'school': 'School1' },
{ 'name':'A', 'age': 17, 'marks': 60, 'school': 'School1' },
upsert=True )
print post1
print post2
1 个回答
0
根据文档,update
这个方法会返回:
一个描述更新效果的文档(字典),或者如果写入确认被禁用,则返回
None
。
你可以试试这个方法,然后用print
打印返回值,看看有什么内容。你会看到类似下面的东西:
{u'syncMillis': 0, u'ok': 1.0, u'err': None, u'writtenTo': None,
u'connectionId': 190, u'n': 1, u'updatedExisting': True}
你需要关注的字段是updatedExisting
。