1

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.

TheStranger
  • 1,387
  • 1
  • 13
  • 35

2 Answers2

2

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

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      applicationIds: {
        $cond: {
          if: { $ne: [ { $type: "$applicationIds" }, "missing" ] },
          then: { type: "linux", refId: "$applicationIds" },
          else: {}
        }
      },
      configurationIds: {
        $cond: {
          if: { $ne: [ { $type: "$configurationIds" }, "missing" ] },
          then: { type: "linux", refId: "$configurationIds" },
          else: {}
        }
      }
    }
  }
])

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 it

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      applicationIds: {
        $cond: {
          if: { $ne: [ { $type: "$applicationIds" }, "missing" ] },
          then: { type: "linux", refId: "$applicationIds" },
          else: "$$REMOVE"
        }
      },
      configurationIds: {
        $cond: {
          if: { $ne: [ { $type: "$configurationIds" }, "missing" ] },
          then: { type: "linux", refId: "$configurationIds" },
          else: "$$REMOVE"
        }
      }
    }
  }
])

playground

cmgchess
  • 7,996
  • 37
  • 44
  • 62
0
db.myCollection.aggregate([
   {
      $project: {
         fieldToProject: {
            $cond: {
               if: { $exists: ["$specificField", true] },
               then: "$specificField",
               else: null
            }
         }
      }
   }
])
  • did you test this. says exists doesnt work here – cmgchess Apr 20 '23 at 15:17
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 24 '23 at 20:20