Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-10022

Docs for SERVER-27614: provide aggregation expression to remove field: $$REMOVE

      Documentation Request Summary:

      Add docs for the new REMOVE variable here: https://docs.mongodb.com/manual/reference/aggregation-variables/.

      Engineering Ticket Description:

      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:
            kay.kim@mongodb.com Kay Kim (Inactive)
            Reporter:
            emily.hall Emily Hall
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved:
              6 years, 40 weeks, 2 days ago