mongodb中使用c#驱动程序的条件投影



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

我的文档:

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

这就是我要做的。为了让你删除组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'}
}},

](

最新更新