其想法是将某种行号返回给mongodb聚合命令/管道。类似于我们在RDBM中所做的。
它应该是唯一的数字,如果它与行/数字完全匹配,则不重要。
对于像这样的查询:
[ { $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吗?
发布于 2017-02-07 23:39:01
不确定在大型查询中的性能,但这至少是一个选择。
您可以通过分组/推送将结果添加到数组中,然后使用includeArrayIndex展开,如下所示:
[
{$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中,您就可以获得实际位置,而不必推送所有结果来枚举它们。
发布于 2021-05-14 20:07:19
另一种方法是使用"$function“跟踪row_number
[{ $match: { "author" : { $ne: 1 } }} , { $limit: 1000000 },
{
$set: {
"rownum": {
"$function": {
"body": "function() {try {row_number+= 1;} catch (e) {row_number= 0;}return row_number;}",
"args": [],
"lang": "js"
}
}
}
}]不过,我不确定这是否会把事情搞砸!
发布于 2021-11-27 19:26:24
从Mongo 5开始,这是新的$setWindowFields 聚合运算符及其$documentNumber操作的完美用例:
// { x: "a" }
// { x: "b" }
// { x: "c" }
// { x: "d" }
db.collection.aggregate([
{ $setWindowFields: {
sortBy: { _id: 1 },
output: { rowNumber: { $documentNumber: {} } }
}}
])
// { x: "a", rowNumber: 1 }
// { x: "b", rowNumber: 2 }
// { x: "c", rowNumber: 3 }
// { x: "d", rowNumber: 4 }$setWindowFields允许我们在了解以前或之后的文档的情况下为每个文档工作。这里我们只需要文档在整个集合中的位置(或聚合中间结果)的信息,如$documentNumber所提供的。
注意,因为sortBy参数是必需的,所以我们按_id排序,但实际上,由于您并不关心行的顺序,所以它可以是您想要的任何值。
https://stackoverflow.com/questions/35174554
复制相似问题