Add some kind of row number to a mongodb aggregate command / pipeline

前端 未结 1 481
故里飘歌
故里飘歌 2020-11-28 16:21

The idea is to return a kind of row number to a mongodb aggregate command/ pipeline. Similar to what we\'ve in an RDBM.

It should be a unique number, not important

相关标签:
1条回答
  • 2020-11-28 16:40

    Not sure about the performance in big queries, but this is at least an option.

    You can add your results to an array by grouping/pushing and then unwind with includeArrayIndex like this:

    [
      {$match: {author: {$ne: 1}}},
      {$limit: 10000},
      {$group: {
        _id: 1,
        book: {$push: {title: '$title', author: '$author', copies: '$copies'}}
      }},
      {$unwind: {path: '$book', includeArrayIndex: 'rownum'}},
      {$project: {
        author: '$book.author',
        title: '$book.title',
        copies: '$book.copies',
        rownum: 1
      }}
    ]
    

    Now, if your database contains a big amount of records, and you intend to paginate, you can use the $skip stage and then $limit 10 or 20 or whatever you want to display per page, and just add the number from the $skip stage to your rownum and you'll get the real position without having to push all your results to enumerate them.

    0 讨论(0)
提交回复
热议问题