简体   繁体   中英

MongoDB (PyMongo) Pagination with distinct not giving consistent result

I am trying to achieve pagination with distinct using pymongo.

I have records

{
  name: string,
  roll: integer,
  address: string,
  .
  .
}

I only want name for each record, where name can be duplicate, so i want distinct name with pagination.

result = collection.aggregate([
    {'$sort':{"name":1}},
    {'$group':{"_id":"$name"}},
    {'$skip':skip},
    {'$limit':limit}
])

Problem is, with this query, each time I query I get different result for same page number

Looked into this answer

Distinct() command used with skip() and limit()

but didn't help in my case.

How do I resolve this.

Thanks in advance!

I've tried to sort after the group and it seems to solve the problem

db.collection.aggregate([
  {
    "$group": {
      "_id": "$name"
    }
  },
  {
    "$sort": {
      "_id": 1
    }
  },
  {
    "$skip": 0
  },
  {
    "$limit": 1
  }
])

try it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM