问题描述
这个想法是将一种行号返回到 mongodb 聚合命令/管道.类似于我们在 RDBM 中的内容.
它应该是一个唯一的数字,如果它与行/数字完全匹配并不重要.
对于像这样的查询:
[ { $match: { 作者";: { $ne: 1 } } }, { $limit: 1000000 } ]
我想回来:
{ "rownum";: 0, "标题";:《宴会》、《作者》:但丁",副本": 2 }{ 行数": 1、标题":《神曲》、《作者》:但丁",副本":1}{ 行数": 2、标题":Ecogues",作者":但丁",副本": 2 }{ 行数": 3、标题":《奥德赛》、《作者》:荷马",副本";: 10 }{ 行数": 4、标题":《伊利亚特》、《作者》:荷马",副本";: 10 }
mongodb可以生成这个rownum
吗?
不确定在大查询中的性能,但这至少是一种选择.
您可以通过分组/推送将结果添加到数组中,然后使用 includeArrayIndex
展开,如下所示:
现在,如果您的数据库包含大量记录,并且您打算进行分页,则可以使用 $skip 阶段,然后使用 $limit 10 或 20 或您想在每页显示的任何内容,然后添加从$skip 阶段到您的 rownum,您将获得实际位置,而无需推送所有结果来枚举它们.
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.
For a query like:
[ { $match: { "author" : { $ne: 1 } } }, { $limit: 1000000 } ]
I'd like to return:
{ "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 }
Is it possible to generate this rownum
in mongodb?
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.
这篇关于向 mongodb 聚合命令/管道添加某种行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!