【问题标题】:What does update() in mongodb returnsmongodb中的update()返回什么
【发布时间】:2014-06-11 17:42:46
【问题描述】:

在为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

【问题讨论】:

    标签: python mongodb mongodb-query database nosql


    【解决方案1】:

    正如update 的docs 所说,该方法返回:

    描述更新效果的文档 (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 字段就是您要查找的内容。

    【讨论】:

      猜你喜欢
      • 2012-06-13
      • 2023-01-07
      • 2022-10-07
      • 1970-01-01
      • 2012-06-02
      • 2013-09-25
      • 1970-01-01
      • 2015-05-20
      • 2011-08-19
      相关资源
      最近更新 更多