Export Pipeline to Python with strings containing single quotes produces Invalid Python

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Unresolved
    • Priority: Major - P3
    • None
    • Affects Version/s: 1.47.1
    • Component/s: Export to Language
    • None
    • Environment:
      OS: Win10
      Additional info: MongoDB Compass 1.47.1
    • None
    • None
    • Developer Tools

      Problem Statement/Rationale

      When an aggregation pipeline has a value (right-hand side) which contains a single-quote, the resulting Python code is invalid. The export defaults to single-quoted strings but doesn't escape those single-quotes inside the string.

      (Aside, when the string contains a double-quote, it gets unnecessarily escaped.)

      Please be sure to attach relevant logs with any sensitive data redacted.
      n/a

      Steps to Reproduce

      Paste this in the Aggregations tab, text mode:

      ```js
      [
      {
      $match: {
      some_text_field: "hello 'XYZ' world", // notice this
      another: "single ' quote", // and this
      unnecessary_escape: 'double " inside', // separate but not an issue
      is_deleted: false,
      created: ISODate("2025-10-15 22:08:59"),
      score:{ $in: [1, 2.5, 1e3, 0.2] }}
      }
      ]
      ```

      Expected Results

      The generated Python should be:

      ```python
      [
      {
      '$match': {
      'is_deleted': False,
      'created': datetime(2025, 10, 15, 16, 38, 59, tzinfo=timezone.utc),
      'some_text_field': 'hello \'XYZ\' world', # properly escaped
      'another': 'single \' quote', # properly escaped
      'unnecessary_escape': 'double " inside', # no need to escape
      'score':

      { '$in': [ 1, 2.5, 1e3, 0.2 ] }

      }
      }
      ]
      ```

      Actual Results

      Notice the single quote not being escaped and results in invalid Python:

      ```python
      [
      {
      '$match': {
      'some_text_field': 'hello 'XYZ' world', # this should have been escaped; or use double-quotes outside
      'another': 'single ' quote', # same
      'unnecessary_escape': 'double \" inside', # unnecessary escape of double-quote inside a single-quoted string
      'is_deleted': False, # other types are fine
      'created': datetime(2025, 10, 15, 16, 38, 59, tzinfo=timezone.utc),
      'score':

      { '$in': [ 1, 2.5, 1e3, 0.2 ] }

      }
      }
      ]
      ```

      Additional Notes

      (Possible that the boolean-flag for `quote strings with single-quote` got flipped when checking for 'single quote in single-quoted-string`)

      Screenshot of how it looks in Compass:

            Assignee:
            Unassigned
            Reporter:
            Anirudh Dutt
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: