将某种行号添加到mongodb聚合命令/管道 [英] Add some kind of row number to a mongodb aggregate command / pipeline
问题描述
这个想法是将一种行号返回到mongodb聚合命令/管道.与RDBM中的类似.
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 if it matches exactly to a row/number.
对于像这样的查询:
[ { $match: { "author" : { $ne: 1 } }} , { $limit: 1000000 } ]
返回:
{ "rownum" : 0, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "rownum" : 1, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "rownum" : 2, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "rownum" : 3, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "rownum" : 4, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
是否可以在mongodb中生成该rownum?
Is it possible to generate this rownum in mongodb ?
推荐答案
不确定大型查询的性能,但这至少是一个选择.
Not sure about the performance in big queries, but this is at least an option.
您可以通过分组/推入将结果添加到数组中,然后使用includeArrayIndex
展开,如下所示:
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
}}
]
现在,如果您的数据库包含大量记录,并且您打算分页,则可以使用$ skip阶段,然后使用$ limit 10或20或要在每页上显示的任何内容,然后将将$ skip阶段移至您的rownum,您将获得真实位置,而不必将所有结果都进行枚举.
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.
这篇关于将某种行号添加到mongodb聚合命令/管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!