【问题标题】:Unrecognized expression '$first'无法识别的表达式“$first”
【发布时间】: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


【解决方案1】:

来自Documentation:4.4 版中的新增功能

请注意,您尝试使用的是 $first 数组元素运算符,与 $group 阶段中可用的 $first aggregation accumulator 不同。

【讨论】:

  • 是的... 4.4版本的文档。但在4.2中不存在,这是@Shadoweb使用的版本
猜你喜欢
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多