首页 > 代码库 > mongodb study

mongodb study

mongodb study

  • 读到101个记录不动了,卡住的语句好像是网络不通:

File “/Library/Python/2.7/site-packages/pymongo/cursor.py”, line 1058, in next

if len(self.__data) or self._refresh():

File “/Library/Python/2.7/site-packages/pymongo/cursor.py”, line 1019, in _refresh

limit, self.__id))

File “/Library/Python/2.7/site-packages/pymongo/cursor.py”, line 915, in __send_message

res = client._send_message_with_response(message, **kwargs)

File “/Library/Python/2.7/site-packages/pymongo/mongo_client.py”, line 1198, in _send_message_with_response

response = self.__send_and_receive(message, sock_info)

File “/Library/Python/2.7/site-packages/pymongo/mongo_client.py”, line 1175, in __send_and_receive

return self.__receive_message_on_socket(1, request_id, sock_info)

File “/Library/Python/2.7/site-packages/pymongo/mongo_client.py”, line 1167, in __receive_message_on_socket

return self.__receive_data_on_socket(length - 16, sock_info)

File “/Library/Python/2.7/site-packages/pymongo/mongo_client.py”, line 1146, in __receive_data_on_socket

chunk = sock_info.sock.recv(length)

把无线网络换成有线网络就不没问题

  • 读了大概一万多条记录之后,又报错:

pymongo.errors.CursorNotFound: cursor id ‘99728967371‘ not valid at server

解决方法参考:

  • stackoverflow: mongodb-cursor-id-not-valid-error

  • 解决 MongoDB 的 cursor id is not valid at server 问题


  • mongodb是实际就是存储文本,文本格式为json。每个相同格式的集合称为collection,对应关系数据库里的tablecollection的创建不需要规定格式和字段

  • mongodb的collection的添加在服务端不会做任何校验,因此添加记录时候要特别小心,比如一个拼写错误,会导致你都不知道数据存在什么地方

  • 枚举记录

    for item in mongoDb[‘sems‘].find():
        print item
  • mongodb添加记录之后会做自动索引Object ID,这个Object ID相当于关系数据库的自动计数(auto-increment primary keys)。

  • Object ID里含有时间信息:

    def covert_time_from_objectid(objectid):
    result = 0
    try:
        timezoneLocal = pytz.timezone(‘Asia/Shanghai‘)
        timeLocal = objectid.generation_time.astimezone(timezoneLocal)
        result = timeLocal.strftime("%Y-%m-%d %H:%M:%S")
    except:
        print "error when converting obj id"
    return result

mongodb study