无法识别的表达式'$ first' [英] Unrecognized expression '$first'
问题描述
我需要从数组中提取第一项并将其添加到其自己的对象中,所以我发现$ first确实做到了 https://docs.mongodb.com/manual/reference/operator/aggregation/first-array-element/#example
但是,我得到了错误无法识别的表达式'$ first'
,并认为这是我的查询无法正常工作,因此我克隆了他们在文档中的确切示例,但它给了我相同的答案错误.
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" } } }
])
预期:文档期望什么.
收到:无法识别的表达式'$ first'
Expected: What the doc is expecting.
Received: Unrecognized expression '$first'
修改
我发现了使用 {$ addFields:{firstrun:{$ arrayElemAt:[" $ log',0]}}}
的另一种方法,但我仍然很好奇关于以上
I found out another way to do the same thing with { $addFields: { firstrun: { $arrayElemAt: [ "$log", 0 ] } } }
but still I'm curious about the above
推荐答案
来自文档:版本4.4中的新内容
From the Documentation : new in version 4.4
请注意,您尝试使用的是$ first数组元素运算符,它不同于 $ first聚合累加器在$ group阶段可用.
Be careful, the one you try to use is the $first array element operator, different from the $first aggregation accumulator available in $group stage.
这篇关于无法识别的表达式'$ first'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!