|
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" }
|
|