I have the following project:
{
'$project': {
'_id': 1,
'applicationIds': {
'type': 'linux',
'refId': '$applicationIds'
},
'configurationIds': {
'type': 'linux',
'refId': '$configurationIds'
}
}
}
As long as there is at least one record in $configurationIds
I will get something like this:
{
'type': 'linux',
'refId': ObjectId('...')
}
And same with $applicationIds
..
The issue arises when there are no records in $configurationIds
or $applicationIds
then I get this:
{
'type': 'linux'
}
I don’t want this, if there are no $applicationIds
, I just want the object to be empty.
Btw I do an $unwind
on $applicationIds
(with preserveNullAndEmptyArrays) just before this stage so there can only be either one or no applicationIds in each document. Same goes for applicationIds.
2
Answers
you can write a condition to check if the field is missing or not. This post shows a way to check that and if doesn’t exists project an empty object
playground
if you don’t want the non existing field after projecting as well instead of the empty object you can use
$$REMOVE
. This post has some example usage of itplayground