skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. db.myCollection.aggregate([
       {
          $project: {
             fieldToProject: {
                $cond: {
                   if: { $exists: ["$specificField", true] },
                   then: "$specificField",
                   else: null
                }
             }
          }
       }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search