MongoDB:聚合字段包含点

MongoDB: aggregation with field containing dot

我有一个文档集合,其中一个字段名称似乎有一个点:

{

"prod_id": "123",
"prod_cost (whole)": 49
"prod_cost (dec.)": 49
}

我怎样才能有效地运行一个使用该字段的聚合管道?

截至目前,它报告空值,因为它将“)”视为 “prod_cost(dec.)”的附加嵌套字段。

来自 MongoDB version 5

MongoDB 5.0 adds improved support for the use of ($) and (.) in field names. There are some restrictions. See Field Name Considerations for more details.

Field Names with Periods (.) and Dollar Signs ($)

In most cases data that has been stored using field names like these is not directly accessible. You need to use helper methods like $getField, $setField, and $literal in queries that access those fields.

{ "$getField": "prod_cost (dec.)" }

Sample MongoPlayground

访问对象中的字段,可以参考Query a Field in a Sub-documentdemo

{
  "$getField": {
    field: {
      $literal: "prod_cost (dec.)"
    },
    input: "$productInfo"
  }
}

Sample Mongo Playground (Nested object)