【问题标题】:Conditional projection in mongodb using c# driver使用 c# 驱动程序在 mongodb 中进行条件投影
【发布时间】:2020-09-25 11:55:50
【问题描述】:

我想有条件地从投影中排除一个字段。以下是我的文档,如果课程类型是英语,我想排除教授的投影。

我的文档:

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

预期结果:

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

我们可以使用 C# 驱动程序实现这一点吗?如果可以,请分享一个示例。

【问题讨论】:

  • 到目前为止你尝试过什么?向我们展示您的代码并尝试解释您遇到的问题,以便我们为您提供帮助。

标签: c# mongodb aggregation-framework projection


【解决方案1】:

这就是我的做法。为了让您删除组 ID“工件”,那么您必须投影组输出并且不包含该 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'}
}},

])

【讨论】:

  • 我刚刚意识到您正在寻找 C# 驱动程序解决方案。对不起!
猜你喜欢
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多