使用 c# 驱动程序在 mongodb 中进行条件投影 [英] Conditional projection in mongodb using c# driver

查看:99
本文介绍了使用 c# 驱动程序在 mongodb 中进行条件投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的文档:

{
  "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# 驱动程序来实现这一点吗?如果可以,请分享一个示例.

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

推荐答案

这就是我要做的.为了让你删除组idartifact"那么你将不得不投影组输出而不包括 id.

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

] )

这篇关于使用 c# 驱动程序在 mongodb 中进行条件投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆