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.

1
  • What have you tried so far? Show us your code and try to explain where you stuck so that we can help you. Commented Sep 25, 2020 at 12:02

1 Answer 1

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'}
}},

] )

Sign up to request clarification or add additional context in comments.

1 Comment

I just realized you were looking for a C# driver solution. Sorry!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.