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

No obvious way to replace existing array with a single document through $project

    • Query Optimization

      When using $project, replacing the contents of an existing array with a field will replace the entire array with that field. However, replacing the content of an existing array with a document will replace every element in the array with that document.

      > db.collection.aggregate({$project: {_id:0, array:1}})
      { "array" : [ 1, 2, 3 ] }
      > db.collection.aggregate({$project: {_id:0, array:"pie" }})
      { "array" : "pie" }
      > db.collection.aggregate({$project: {_id:0, array:{snack:"pie"} }})
      { "array" : [ { "snack" : "pie" }, { "snack" : "pie" }, { "snack" : "pie" } ] }
      
      Original Description

      As per this post on SO: https://stackoverflow.com/a/52822987/6440033 and this playground:
      https://mongoplayground.net/p/wdMj4ZQAHhc there is some unexpected behaviour when attempting to replace the contents of an array field using a nested $map operator.

            Assignee:
            backlog-query-optimization [DO NOT USE] Backlog - Query Optimization
            Reporter:
            daniel.hegener@gmx.net Daniel Hegener
            Votes:
            0 Vote for this issue
            Watchers:
            9 Start watching this issue

              Created:
              Updated: