pymongo 查询排序操作(参数与函数调用查询对比)

官方文档中,find 函数中的说明表明,在 find 中传参应该和 cursor 后面调用 sort 函数一样
升序:pymongo.ASCENDING ( 1 )
降序:pymongo.DESCENDING ( -1 )

find(filter=None, projection=None, skip=0, limit=0, no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE, sort=None, allow_partial_results=False, oplog_replay=False, modifiers=None, manipulate=True)

sort 作为入参查询方式

collection = db_conn[collection_name]
result = collection.find( query_conditioin, projection={"_id":True, "dev_status":True, "created_at":True}, limit=3, sort=[("created_at",pymongo.ASCENDING)] )

sort 函数调用方式

collection = db_conn[collection_name]
result = collection.find( query_conditioin, projection={"_id":True, "dev_status":True, "created_at":True}).limit(3).sort([("created_at",pymongo.ASCENDING)])

官方源码参数详解:

  • filter (optional): a SON object specifying elements which
    must be present for a document to be included in the
    result set

  • projection (optional): a list of field names that should be
    returned in the result set or a dict specifying the fields
    to include or exclude. If projection is a list “_id” will
    always be returned. Use a dict to exclude fields from
    the result (e.g. projection={‘_id’: False}).

  • skip (optional): the number of documents to omit (from
    the start of the result set) when returning the results

  • limit (optional): the maximum number of results to
    return

  • no_cursor_timeout (optional): if False (the default), any
    returned cursor is closed by the server after 10 minutes of
    inactivity. If set to True, the returned cursor will never
    time out on the server. Care should be taken to ensure that
    cursors with no_cursor_timeout turned on are properly closed.

  • cursor_type (optional): the type of cursor to return. The valid
    options are defined by :class:~pymongo.cursor.CursorType:

    • :attr:~pymongo.cursor.CursorType.NON_TAILABLE - the result of
      this find call will return a standard cursor over the result set.
    • :attr:~pymongo.cursor.CursorType.TAILABLE - the result of this
      find call will be a tailable cursor - tailable cursors are only
      for use with capped collections. They are not closed when the
      last data is retrieved but are kept open and the cursor location
      marks the final document position. If more data is received
      iteration of the cursor will continue from the last document
      received. For details, see the tailable cursor documentation
      <http://www.mongodb.org/display/DOCS/Tailable+Cursors>
      _.
    • :attr:~pymongo.cursor.CursorType.TAILABLE_AWAIT - the result
      of this find call will be a tailable cursor with the await flag
      set. The server will wait for a few seconds after returning the
      full result set so that it can capture and return additional data
      added during the query.
    • :attr:~pymongo.cursor.CursorType.EXHAUST - the result of this
      find call will be an exhaust cursor. MongoDB will stream batched
      results to the client without waiting for the client to request
      each batch, reducing latency. See notes on compatibility below.
  • sort (optional): a list of (key, direction) pairs
    specifying the sort order for this query. See
    :meth:~pymongo.cursor.Cursor.sort for details.

  • allow_partial_results (optional): if True, mongos will return
    partial results if some shards are down instead of returning an
    error.

  • oplog_replay (optional): If True, set the oplogReplay query
    flag.

  • batch_size (optional): Limits the number of documents returned in
    a single batch.

  • manipulate (optional): DEPRECATED - If True (the default),
    apply any outgoing SON manipulators before returning.

  • collation (optional): An instance of
    :class:~pymongo.collation.Collation. This option is only supported
    on MongoDB 3.4 and above.

  • return_key (optional): If True, return only the index keys in
    each document.

  • show_record_id (optional): If True, adds a field $recordId in
    each document with the storage engine’s internal record identifier.

  • snapshot (optional): If True, prevents the cursor from returning
    a document more than once because of an intervening write
    operation.

  • hint (optional): An index, in the same format as passed to
    :meth:~pymongo.collection.Collection.create_index (e.g.
    [('field', ASCENDING)]). Pass this as an alternative to calling
    :meth:~pymongo.cursor.Cursor.hint on the cursor to tell Mongo the
    proper index to use for the query.

  • max_time_ms (optional): Specifies a time limit for a query
    operation. If the specified time is exceeded, the operation will be
    aborted and :exc:~pymongo.errors.ExecutionTimeout is raised. Pass
    this as an alternative to calling
    :meth:~pymongo.cursor.Cursor.max_time_ms on the cursor.

  • max_scan (optional): The maximum number of documents to scan.
    Pass this as an alternative to calling
    :meth:~pymongo.cursor.Cursor.max_scan on the cursor.

  • min (optional): A list of field, limit pairs specifying the
    inclusive lower bound for all keys of a specific index in order.
    Pass this as an alternative to calling
    :meth:~pymongo.cursor.Cursor.min on the cursor.

  • max (optional): A list of field, limit pairs specifying the
    exclusive upper bound for all keys of a specific index in order.
    Pass this as an alternative to calling
    :meth:~pymongo.cursor.Cursor.max on the cursor.

  • comment (optional): A string or document. Pass this as an
    alternative to calling :meth:~pymongo.cursor.Cursor.comment on the
    cursor.

  • modifiers (optional): DEPRECATED - A dict specifying
    additional MongoDB query modifiers. Use the keyword arguments listed
    above instead.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在使用 PyMongo 查询 MongoDB 数据库时,可以使用 `limit` 和 `skip` 方法实现分页查询。 `limit` 方法用于限制查询结果的数量,而 `skip` 方法用于跳过一定数量的查询结果。结合使用这两个方法可以实现分页查询。例如: ```python import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] collection = db["mycollection"] # 每页显示的数量 page_size = 10 # 第几页,从1开始 page_num = 1 # 计算跳过的数量 skip_num = (page_num - 1) * page_size # 查询并分页 results = collection.find().skip(skip_num).limit(page_size) for result in results: print(result) ``` 在上面的例子中,我们首先创建了 `MongoClient` 对象,并指定了连接的 MongoDB 地址和端口。然后选择了要查询的数据库和集合。 接着,我们指定了每页显示的数量和要查询的页数。然后计算出需要跳过的数量,即 `(page_num - 1) * page_size`。最后使用 `find` 方法查询数据,并通过 `skip` 方法跳过一定数量的结果,再使用 `limit` 方法限制返回的结果数量。 最后,我们遍历查询结果并输出。 ### 回答2: pymongo是Python中用于操作MongoDB数据库的驱动程序。在进行查询分页时,可以使用pymongo提供的`find()`方法结合`skip()`和`limit()`实现。具体步骤如下: 1. 导入pymongo模块并连接MongoDB数据库: ```python import pymongo client = pymongo.MongoClient('<数据库URL>') db = client['<数据库名称>'] collection = db['<集合名称>'] ``` 2. 定义每页显示的记录数和要查询的页数: ```python page_size = 10 # 每页显示的记录数 page_number = 1 # 要查询的页数 ``` 3. 计算要跳过的记录数,并进行查询: ```python skip_count = (page_number - 1) * page_size results = collection.find().skip(skip_count).limit(page_size) ``` 4. 遍历查询结果: ```python for result in results: print(result) ``` 这样就能够实现MongoDB数据库的查询分页了。其中,`skip()`用于跳过指定数量的记录,`limit()`用于限制查询结果返回的记录数。根据需要,可以根据当前页数和每页记录数来动态地计算应该跳过多少条记录和返回多少条记录。 ### 回答3: Pymongo是一个用于连接MongoDB数据库的Python驱动程序。对于查询分页,我们可以使用limit()和skip()方法来实现。 limit()方法用于限制查询结果返回的文档数目,而skip()方法则用于跳过指定数量的文档。通过这两个方法的组合,我们可以实现分页查询。 假设我们有一个名为"users"的集合,其中包含了很多文档。要实现分页查询,我们首先需要确定每页显示的文档数量,并计算出总页数。 假设每页显示10条文档,我们可以使用如下代码实现第1页的查询: ```python from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client['testdb'] collection = db['users'] page_size = 10 # 每页显示的文档数量 page_number = 1 # 当前页码 result = collection.find().skip((page_number - 1) * page_size).limit(page_size) for doc in result: print(doc) ``` 在上述代码中,我们先计算出要跳过的文档数量,即(page_number - 1) * page_size,然后使用skip()方法跳过这些文档,再使用limit()方法只返回指定数量的文档。 如果要查询第2页,只需要将page_number设置为2即可。同理,要查询其他页也是如此。这里需要注意,我们的代码没有处理总页数和当前页码是否合法的情况,需要根据实际情况进行适当的处理。 总之,通过使用Pymongo的limit()和skip()方法,我们可以轻松实现MongoDB的查询分页功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值