【问题标题】:MongoDB Aggregation: Unable to reference fields using $condMongoDB 聚合:无法使用 $cond 引用字段
【发布时间】:2019-06-17 08:05:15
【问题描述】:

我正在对 MongoDB 集合执行聚合。主题$cond 之前的步骤并不重要,因此为了简洁起见,我将对其进行编辑:

db.mycoll.aggregate([
  { $match: ... },
  { $project: ... },
  { /* this is the problem step */ }
])

第 2 步生成的文档$project 的形状如下:

{
  "blueTeam": true,
  "redTeam": false,
  "winner": true
}

现在假设我添加了一个使用 $cond 的附加投影 - 我不允许处理投影文档中的字段。这是一个天真的例子:

{
  $project: {
    blueTeam: "$blueTeam",
    winnerAsInteger: {
      $cond: [ { "$winner": true }, 1, 0 ]
    }
  }
}

期望:管道发出文档,其中获胜文档的字段 winnerAsInteger 等于 1,否则为 0。

现实:此管道步骤会产生错误。

在Node的MongoDB客户端,报错如下:

(node:34380) UnhandledPromiseRejectionWarning: MongoError: Unrecognized expression '$winner'

在 MongoDB Compass 的聚合 GUI 中,错误是:

字段不能以“$”或“.”开头,字段路径为:$winner

这似乎与 the documentation 直接矛盾,后者使用 $ 语法引用文档字段。

我在 MongoDB 4.0.5 上,物有所值。

【问题讨论】:

  • 试试{$eq:[ "$winner", true ]} 而不是{ "$winner": true }
  • @Veeram 是的,这行得通。如果你想回答这个问题,我可以给它信用。

标签: mongodb aggregation-framework


【解决方案1】:

试试

{$eq:[ "$winner", true ]} instead of { "$winner": true }

感谢 cmets 中的 @s7vr,只是将其添加到此处,以免人们认为这是一个未解决的问题!

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2016-05-30
    • 2023-03-22
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    相关资源
    最近更新 更多