Mongo 聚合 $match 基于计算值的相等表达式

问题描述 投票:0回答:1

我正在尝试检索注册日期为 2007 年的所有用户。我的语法似乎有问题。我不知道在哪里放置等式表达式,但这会给出以下错误:

 MongoServerError: unknown top level operator: $year. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.

db.users.aggregate([
    {
        $match: { $year: { $convert: { input: "$registered.date", to: "date" } } },
    },
    {$project:{_id:0, name:1}}
])

我知道 $convert string to date 代码正在工作,因为我把它放在

$project
中并且它正在工作:

db.users.aggregate([
    {
      $project: {
        year: { $year: { $convert: { input: "$registered.date", to: "date" } } }
      },
    },
  ]); --> printing out the correct years

如何在 match 子句中使用此 $year 值执行限制以仅限制 2007 年?

mongodb aggregation-framework
1个回答
0
投票

问题是在

$match
阶段你无法从聚合算子入手。您需要
$expr
才能使用聚合运算符。

{
  $match: {
    $expr: {
      $eq: [
        {
          $year: {
            $convert: {
              input: "$registered.date",
              to: "date"
            }
          }
        },
        2007
      ]
    }
  }
}

演示@Mongo Playground

请注意,

$convert
运算符可以使用
$toDate
运算符进行简化。

$toDate: "$registered.date"
© www.soinside.com 2019 - 2024. All rights reserved.