Unrecognized expression '$first'

Viewed 5733

I need to extract the first item from an array and add it to its own object, so I found $first the does exactly that https://docs.mongodb.com/manual/reference/operator/aggregation/first-array-element/#example
However, I was getting the error Unrecognized expression '$first' and thought it was my query that wasn't working, so I cloned the exact example they have in their docs, but it gives me the same error.

db.runninglog.insertMany([
 { "_id" : 1, "team" : "Anteater", log: [ { run: 1, distance: 8 }, { run2: 2, distance: 7.5 }, { run: 3, distance: 9.2 } ] },
 { "_id" : 2, "team" : "Bears", log: [ { run: 1, distance: 18 }, { run2: 2, distance: 17 }, { run: 3, distance: 16 } ] },
 { "_id" : 3, "team" : "Cobras", log: [ { run: 1, distance: 2 } ] }
])

db.runninglog.aggregate([
 { $addFields: { firstrun: { $first: "$log" }, lastrun: { $last: "$log" } } }
])

Expected: What the doc is expecting.
Received: Unrecognized expression '$first'

Edit

I found out another way to do the same thing with { $addFields: { firstrun: { $arrayElemAt: [ "$log", 0 ] } } } but still I'm curious about the above

1 Answers
Related