mongodb中的update()返回什么

时间:2014-06-11 17:42:47

标签: python mongodb mongodb-query database nosql

在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 :(得分:0)

正如update的{​​{3}}所说,该方法返回:

  

描述更新效果的文档(dict)或禁用写入确认时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字段。