【发布时间】:2020-11-20 18:47:38
【问题描述】:
我需要从数组中提取第一项并将其添加到它自己的对象中,所以我发现 $first 正是 https://docs.mongodb.com/manual/reference/operator/aggregation/first-array-element/#example
但是,我收到错误 Unrecognized expression '$first' 并认为是我的查询不起作用,所以我克隆了他们在文档中的确切示例,但它给了我同样的错误。
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" } } }
])
预期:文档的预期。
收件:Unrecognized expression '$first'
编辑
我发现了另一种使用 { $addFields: { firstrun: { $arrayElemAt: [ "$log", 0 ] } } } 做同样事情的方法,但我仍然对上述内容感到好奇
【问题讨论】:
-
看来工作正常here
-
您使用的是哪个版本的 mongodb? `$addFields' 从 3.4 版添加
-
正在 Atlas 中运行该命令,似乎是一个错误 @eshirvana。不确定指南针
-
MongoDB 4.2.10 企业版。 Compass 1.23.0 版(但在代码和命令行上也失败了)。
-
我应该将其报告为错误吗?
标签: mongodb aggregation-framework