Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-91784

$project-$addFields on arrays can produce incorrect results

    • Query Execution
    • Fully Compatible
    • ALL
    • v8.0, v7.3, v7.0, v6.0, v5.0
    • QE 2024-07-08
    • 200

      Consider the following pipeline:

      [
        {$documents: [{a: [1, 2, 3]}]},
        {$project: {"a.b": 1}},
        {$addFields: {"a.c": "why?"}}
      ]
      

      Inclusion $project on a sub-field of an array will remove all scalar values, making array “a” empty.
      $addFields on a sub-field of an array will add

      {c: “why?“}

      to every element of the array, but array is empty, so the expected answer would be

      [{a: []}]
      

      However, we get

      { a: [ { c: 'why?' }, { c: 'why?' }, { c: 'why?' } ] }
      

      because $project actually doesn't remove scalars, but replacing them with MISSING values.

      This is a bug. Especially given it behaves inconsistently with reading from disk,
      because this pipeline will return correct result.
      Consider a collection test with a single document

      {a: [1, 2, 3]}
      db.test.aggregate([{$project: {_id: 0, "a.b": 1}}, {$addFields: {"a.c": "why?"}}]).
      

      It will return correctly, because if Document has a backing BSONObj, it will use fast-path projection that actually removes elements from the array.

            Assignee:
            ivan.fefer@mongodb.com Ivan Fefer
            Reporter:
            matt.boros@mongodb.com Matt Boros
            Votes:
            0 Vote for this issue
            Watchers:
            10 Start watching this issue

              Created:
              Updated:
              Resolved: