Unrecognized expression '$first'

谁都会走 提交于 2021-01-29 21:50:53

问题


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:


From the Documentation : new in version 4.4

Be careful, the one you try to use is the $first array element operator, different from the $first aggregation accumulator available in $group stage.



来源:https://stackoverflow.com/questions/64935182/unrecognized-expression-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!