1

I want to conditionally exclude a field from the projection. Below is my document and I want to execlude projection of Professors if the class type is English.

My document:

{
  "Name": "HumanName",
  "Occupation": "Student",
  "Class": [
    {
      "ClassType": "Math",
      "Professors": [
        {
          "Name": "Jimmy"
        },
        {
          "Name": "Smith"
        }
      ]
    },
    {
      "ClassType": "English",
      "Professors": [
        {
          "Name": "John"
        }
      ]
    }
  ]
}

Exprected result:

{
  "Name": "HumanName",
  "Occupation": "Student",
  "Class": [
    {
      "ClassType": "Math",
      "Professors": [
        {
          "Name": "Jimmy"
        },
        {
          "Name": "Smith"
        }
      ]
    },
    {
      "ClassType": "English",
      "Professors": []
    }
  ]
}

Can we achieve this using C# driver and if we can please share a example.

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28

1 Answers1

0

This is how I would go about it. In order for you to remove the group id "artifact" then you would have to project the group output and not include the id.

db.getCollection('MyClass').aggregate( [
{$unwind: '$Class'}, 
{ $project : {  Name : 1 , 
                Occupation : 1, 
                Class : {
                    ClassType:1, 
                    Professors:{
                        $cond: {
                            if: { $eq: ["$Class.ClassType", "English"] },
                            then: [],
                            else: "$Class.Professors"
                                }
                    }
                }
            } 
    },
{$group: {
    _id: '$_id',
    Name: {$first: '$Name'},
    Occupation: {$first: '$Occupation'},
    Class: {$push: '$Class'}
}},

] )

SJFJ
  • 657
  • 6
  • 18