MongoError: Unrecognized expression '$last' ("version": "5.0.4")

MongoError: Unrecognized expression '$last' ("version": "5.0.4")

当我尝试聚合投影时

我正在使用这个 MongoDB 版本(“版本”:“5.0.4”)

                {
                    $project: {
                        _id: 1,
                        feeling: 1,
                        updated_date: 1,
                        created_date: 1,
                        activity_type: 1,
                        activityCount: { $size: "$activity" },
                        activity_count: 1,
                        activity_tipped_count: 1,
                        activity_upvote_count: 1,
                        activity: { $last: "$activity" },
                        product: 1,
                        property: 1,
                        shared_post: 1,
                        post: 1,
                        user: 1,
                        rss_delete: 1,
                    },
                },

它给出了这个错误

MongoError: Unrecognized expression '$last'
    at Connection.<anonymous> (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/pool.js:453:61)
    at Connection.emit (node:events:390:28)
    at Connection.emit (node:domain:475:12)
    at processMessage (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/connection.js:456:10)
    at Socket.<anonymous> (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/connection.js:625:15)
    at Socket.emit (node:events:390:28)
    at Socket.emit (node:domain:475:12)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
  ok: 0,
  code: 168,
  codeName: 'InvalidPipelineOperator'
}

在此先感谢任何帮助对我来说意义重大

我猜测这是驱动程序未能区分 $last 聚合累加器和 $arrayElemAt(-1) 的 $last 别名。根据 https://docs.mongodb.com/manual/reference/operator/aggregation/last/ 上的文档,累加运算符在 $project 阶段无效。

也许尝试用这个替换它:

activity: { $arrayElemAt: [ "$activity", -1 ] }