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

provide aggregation expression to remove field: $$REMOVE

    • Fully Compatible
    • v3.4
    • Query 2017-03-27

      The $project stage supports both inclusion and exclusion based projections. However, there is no way to conditionally exclude a field based on the result of some computation. In order to support this use case, we will add a new system variable REMOVE. When a field f is set to the value of an expression, and that expression evaluates to $$REMOVE, f is excluded from the resulting document.

      Suppose, for example, that you wanted to include the field middleInitial, unless its value was the empty string. This could be achieved as shown below:

      > db.names.drop();
      > db.names.insert({last: "Smith", middleInitial: "H", first: "John"});
      > db.names.insert({last: "Doe", middleInitial: "", first: "Jane"});
      
      // Here we have removed the middleInitial field, but only in those documents where it contained the empty string.
      > db.names.aggregate([{$project: {
          _id: 0,
          last: 1,
          middleInitial: {$cond: {if: {$eq: ["", "$middleInitial"]}, then: "$$REMOVE", else: "$middleInitial"}},
          first: 1
      }}]);
      { "last" : "Smith", "first" : "John", "middleInitial" : "H" }
      { "last" : "Doe", "first" : "Jane" }
      

            Assignee:
            david.storch@mongodb.com David Storch
            Reporter:
            asya.kamsky@mongodb.com Asya Kamsky
            Votes:
            3 Vote for this issue
            Watchers:
            9 Start watching this issue

              Created:
              Updated:
              Resolved: