添加基于排序mongodb聚合展开的秩



我使用includeArrayIndex添加基于排序的秩

这是聚合查询

dbo.collection("funds").aggregate([
{
"$sort": {
"amount": -1
}
},
{
"$group": {
"_id": "",
"items": {
"$push": "$$ROOT"
}
}
},
{
"$unwind": {
"path": "$items",
"includeArrayIndex": "items.rank"
}
},
{
"$replaceRoot": {
"newRoot": "$items"
}
},
{
"$sort": {
"rank": -1
}
}
])

这分配了rank字段,但从0开始,有没有办法从1开始

试过这样的

[
{
'$sort': {
'amount': -1
}
}, {
'$group': {
'_id': '',
'items': {
'$push': '$$ROOT'
}
}
}, {
'$unwind': {
'path': '$items',
'includeArrayIndex': 'items.rank'
}
}, {
'$replaceRoot': {
'newRoot': '$items'
}
},
{
'$set': {
'rank': {
'$add': [
'$rank', 1
]
}
}
},
// {
//   '$sort': {
//     'rank': 1
//   }
// }
]

在mongodb指南针聚合选项卡中,它显示添加了该字段,但当我使用nodejs运行此脚本时,它不会添加rank字段

甚至我也试过

const a = await dbo.collection("funds").aggregate(
[
{
'$sort': {
'amount': 1
}
}, {
'$group': {
'_id': '',
'items': {
'$push': '$$ROOT'
}
}
}, {
'$unwind': {
'path': '$items',
'includeArrayIndex': 'items.rank'
}
}, {
'$replaceRoot': {
'newRoot': '$items'
}
},
{
'$addFields': {
'rank': {
'$add': [
'$rank', 1
]
}
}
}
]
).toArray();

甚至在控制台上打印为

[
{ _id: new ObjectId("6220d2fe20e33d48c865b720"), amount: 1, rank: 1 },
{
_id: new ObjectId("6220d2cf20e33d48c865b71e"),
amount: 10,
rank: 2
},
{
_id: new ObjectId("6220d2f520e33d48c865b71f"),
amount: 12,
rank: 3
}
]

然后试用$setWindowFields

dbo.collection("funds").aggregate( [
{
$setWindowFields: {
sortBy: { amount: -1 },
output: {
rank: {
$rank: {}
}
}
}
}
] )

但它显示

err MongoServerError: Unrecognized pipeline stage name: '$setWindowFields'

示例文档类似

[
{amount : 20, name :""},
{amount : 22, name :""}
]

不确定是否已经回答了这个问题。但你只需要加上{$out:"基金"}在代码的最后。PFB工作代码。。。

const a = await dbo.collection("funds").aggregate(
[
{
'$sort': {
'amount': 1
}
}, {
'$group': {
'_id': '',
'items': {
'$push': '$$ROOT'
}
}
}, {
'$unwind': {
'path': '$items',
'includeArrayIndex': 'items.rank'
}
}, {
'$replaceRoot': {
'newRoot': '$items'
}
},
{
'$addFields': {
'rank': {
'$add': [
'$rank', 1
]
}
}
},
{ $out: "funds" }
], {allowDiskUse:true}
).toArray();

最新更新