在最后一个聚合管道之后,我接收到当前数组:
[{
"cdrId": "61574b3e58fb1cae1494df2c",
"date": "2021-10-01T17:54:06.057Z",
"intentType": "FALLBACK"
},
{
"cdrId": "61574b3e58fb1cae1494df2c",
"date": "2021-10-01T17:54:06.057Z",
"intentType": "FAQ"
},
{
"cdrId": "61570b37522aba5e2f205356",
"date": "2021-10-01T13:20:55.601Z",
"intentType": "TRANS/DISAM"
},
{
"cdrId": "61570b37522aba5e2f205356",
"date": "2021-10-01T13:20:55.601Z",
"intentType": "FAQ"
}]我希望添加一个索引字段,显示对象在数组中的当前位置。输出将如下所示:
[{
"index": 0,
"cdrId": "61574b3e58fb1cae1494df2c",
"date": "2021-10-01T17:54:06.057Z",
"intentType": "FALLBACK"
},
{
"index": 1,
"cdrId": "61574b3e58fb1cae1494df2c",
"date": "2021-10-01T17:54:06.057Z",
"intentType": "FAQ"
},
{
"index": 2,
"cdrId": "61570b37522aba5e2f205356",
"date": "2021-10-01T13:20:55.601Z",
"intentType": "TRANS/DISAM"
},
{
"index": 3,
"cdrId": "61570b37522aba5e2f205356",
"date": "2021-10-01T13:20:55.601Z",
"intentType": "FAQ"
}]如果下一个管道对这个数组进行排序,我将使用这个值。所以在分拣之前我有它原来的位置。
有什么办法能让我用聚合的方式做到这一点吗?我使用的是MongoDB 4.2。
发布于 2021-10-01 19:05:24
试试这个:
db.collection.aggregate([
// {$sort: {...} },
{
$group: {
_id: null,
data: { $push: "$$ROOT" }
}
},
{
$unwind: {
path: "$data",
includeArrayIndex: "index"
}
},
{
$replaceRoot: {
newRoot: { $mergeObjects: [ "$data", {index: "$index"} ] }
}
}
])https://stackoverflow.com/questions/69410321
复制相似问题