pymongo 的使用

来源:互联网 发布:爱玩游戏的女生 知乎 编辑:程序博客网 时间:2024/06/04 22:52

,# pymongo 的使用
+ collection
- 属性:full_name,name,database

  • insert(self, doc_or_docs, manipulate=True, safe=False, check_keys=True, **kwargs):
    • manipulate=True 时,_id 会被自动添加到 dict,并返回些 _id(or list(_id))
    • 为False 时,返回 None
    • 当 safe 为 True 时,会自动判断to_save 是否为 dict,如果检查出错,会提示出错信息,会等待数据库的响应,而不会执行插入数据库
    • doc_or_docs 允许插入一条或多条记录
    • save(self, to_save, manipulate=True, safe=False, **kwargs)
    • to_save,只接受一个 dict (字典)
    • to_save 里包含 _id 时,为update (可能update 多条)
      +drop(self)
    • 删除些 collection (集合及数据一起删除)
  • remove(self, spec_or_id=None, safe=False, **kwargs)
    • 删除操作不可还原
    • 当 safe 为 True 时,会自动判断参数的正确性,如果有异常,会等待数据库的响应,而不会执行删除操作
    • spec_or_id ,为一完整doc 或指定了 _id 的字典
  • find_one(self, spec_or_id=None, *args, **kwargs)
    • spec_or_id ,为一完整doc 或指定了 _id 的字典
    • 返回一条符合条件的记录
    • find(self, *args, **kwargs)
    • 参数必需是一个 doc 原型(eg:{“name”:”abc”})
    • 返回 Cursor ,并非(result collection)
    • spec 查询条件
    • fields 返回的字段清单,但_id 为默认返回
    • skip 省略的记录数
    • limit 一次返回的最大记录数
    • timeout 如果为True ,超时会自动断开
    • snapshot 快照模式,True 时保证返回结果不重复
    • tailable 保持tailable 游标的开启,并记录上次的最后位
    • sort 排序字段
    • max_scan 允许查询的最大数量 ( version >= 1.5.1
    • as_class 指定查询结果的类型,默认为 ~pymongo.connection.Connection.document_class
    • network_timeout 指定超时时间
    • count(self) 返回总记录数
  • create_index(self, key_or_list, deprecated_unique=None, ttl=300, **kwargs)
    • 为一个或多个key创建索引
    • key 必须为字符串类型
    • eg: create_index("mike")
    • eg:create_index([("mike", pymongo.DESCENDING), ("eliot", pymongo.ASCENDING)])
    • ensure_index(self, key_or_list, deprecated_unique=None, ttl=300, **kwargs)
    • 检查是否存在些索引,如果不存在则创建,存在则返回None
    • drop_indexes(self) 删除所以索引
    • drop_index(self, index_or_name) 删除指定索引
    • index_information(self)返回索引信息
    • rename(self, new_name, **kwargs) 重新指向一个collection
    • distinct(self, key) 返回所有key 不重复的记录

以上内容为转载,原文地址:http://kpages.blog.163.com/blog/static/119834863201174101337328/

下面是自己写的
今天遇到了个问题,想在python里创建一个索引(TTL),然后各种百度,也没有找到准确的结果。
报错大概是这样的:
The field 'expiresAfterSeconds' is not valid for an index specification

expireAfterSeconds: Used to create an expiring (TTL)
collection. MongoDB will automatically delete documents from
this collection after seconds. The indexed field must
be a UTC datetime or the data will not expire.

以上取自pymongo的collection

所以用的时候应该这样:

>>> my_collection.create_index([("timestamp"),1],expireAfterSeconds=expiring)
0 0