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

Time:02-15

When I tried to project in aggregate

I am using this MongoDB version ("version": "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,
                    },
                },

It gives this error

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'
}

Thanks in advance any help means a lot for me

CodePudding user response:

I'm guessing that this is a failure in the driver to differentiate between the $last aggregation accumulator and $last alias for $arrayElemAt(-1). Per the documentation at https://docs.mongodb.com/manual/reference/operator/aggregation/last/, the accumulation operator is not valid in a $project stage.

Maybe try replacing it with this:

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

  • Related