Home > database >  MongoDB: aggregation with field containing dot
MongoDB: aggregation with field containing dot

Time:04-09

I have a collection of documents in which a field name appears to have a dot:

{

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

How can I effectively run an aggregation pipeline using that field?

As of now, it reports null values since it considers ")" as an additional nested field for "prod_cost (dec.)".

CodePudding user response:

From 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

To access field in object, you can refer to Query a Field in a Sub-document demo.

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

Sample Mongo Playground (Nested object)

  • Related