如何解决TypeError:spec必须是pymongo上的dict实例

时间:2014-01-17 07:27:37

标签: python mongodb dictionary pymongo

我有一个mongodb集合,我必须根据文档中是否存在子文档来将一些数据插入其中。集合中的示例文档文档是

{"follow_request_sent": "null", 
        "profile_use_background_image": "true", 
        "default_profile_image": "false", 
        "id": 87174680, 
        "verified": "false", 
        "profile_image_url_https": "https://pbs.twimg.com/profile_images/378800000220301249/a0c7b8c5766de83b65a42ca52196c4b3_normal.jpeg", 
        "profile_sidebar_fill_color": "EADEAA", 
        "profile_text_color": "333333", 
        "followers_count": 348, 
        "profile_sidebar_border_color": "D9B17E", 
        "id_str": "87174680", 
        "profile_background_color": "8B542B", 
        "listed_count": 5, 
        "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/350203578/Photo0003.jpg", 
        "utc_offset": 19800, 
        "statuses_count": 20119, 
        "description": "Sports Lover", 
        "friends_count": 708, 
        "location": "India", 
        "profile_link_color": "9D582E", 
        "profile_image_url": "http://pbs.twimg.com/profile_images/378800000220301249/a0c7b8c5766de83b65a42ca52196c4b3_normal.jpeg", 
        "following": "null", 
        "geo_enabled": "true", 
        "profile_background_image_url": "http://a0.twimg.com/profile_background_images/350203578/Photo0003.jpg", 
        "name": "Ronak Baj", 
        "lang": "en", 
        "profile_background_tile": "true", 
        "favourites_count": 17, 
        "screen_name": "ronakbaj", 
        "notifications": "null", 
        "url": "null", 
        "created_at": "Tue Nov 03 12:02:56 +0000 2009", 
        "contributors_enabled": "false", 
        "time_zone": "New Delhi", 
        "protected": "false", 
        "default_profile": "false", 
        "is_translator": "false"
    }, 

我必须根据id的值来更新它,这样如果id已经在文档中,请更新它,否则创建新文档。我用过的语法是:

posts4 = db4.posts
post_id4 = posts4.update(posts4.find_one({'id' : usr.get('id')}), dict4, upsert = True)

dict4是要更新的新文档,如果找到了ID

然而,这给了我一个错误,完整的追溯是:

  File "new.py", line 63, in <module>
    stream.statuses.filter(follow = 95995660)
  File "/usr/lib/python2.7/site-packages/twython/streaming/types.py", line 65, in filter
    self.streamer._request(url, 'POST', params=params)
  File "/usr/lib/python2.7/site-packages/twython/streaming/api.py", line 148, in _request
    if self.on_success(data):  # pragma: no cover
  File "new.py", line 48, in on_success
    post_id4 = posts4.update(posts4.find_one({'id' : usr.get('id')}), dict4, upsert = True)
  File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line 463, in update
    raise TypeError("spec must be an instance of dict")
TypeError: spec must be an instance of dict

请帮助!!

1 个答案:

答案 0 :(得分:1)

要更新的搜索条件在作为update参数传递时必须是字典。 您可以直接传递字典进行更新,如下所示:

posts4 = db4.posts
post_id4 = posts4.update({'id' : usr.get('id')}, dict4, upsert = True)

您可以查看update in mongodb 了解详情