将某种行号添加到 mongodb 聚合命令/管道 [英] Add some kind of row number to a mongodb aggregate command / pipeline

查看:21
本文介绍了将某种行号添加到 mongodb 聚合命令/管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个想法是将一种行号返回到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆