我在 mongo 文档中有这个数组:
"labels" : [
{
"id" : "4b19c495-8c40-4c92-8c7d-ae9fb8defd20",
"labelCategory" : "Content",
"labelType" : "Content_label",
"code" : 5,
"labelName" : "HR Request Forms",
"trustValue" : 1.0,
"riskValue" : 0.0,
"sensitivity" : 0.2,
"concrete" : 0.8,
"threshold" : 2.0,
"abstracts" : [
"707babad-231f-82bb-014c-8506d3dc784e"
]
},
{
"id" : "707babad-231f-82bb-014c-8506d3dc784e",
"labelCategory" : "Content",
"labelType" : "Content_label",
"code" : 5,
"labelName" : "HR Information",
"trustValue" : 1.0,
"riskValue" : 0.0,
"sensitivity" : 0.2,
"concrete" : 0.2,
"threshold" : 2.0,
"abstracts" : []
},
{
"id" : "9cdce502-1dd9-4ef9-b78b-7f7c638490bf",
"labelCategory" : "Virtual",
"labelType" : "Virtual_label",
"code" : 1,
"labelName" : "Object Low Sensitive",
"trustValue" : 1.0,
"riskValue" : 0.0,
"sensitivity" : 0.0,
"concrete" : 0.0,
"threshold" : 0.0,
"abstracts" : []
}
],
现在我只有这个查询:
db.getCollection('objects-89aafe20-780f-46ec-aaa0-a2d95bae542e').find(
{
objectCategory:"Content",
"labels":{
$elemMatch:{"labelCategory" : "Content", labelName:{$ne:"Other"}}
}
},
{objectName:1, _id:0, labels:{labelName:1}}
)
电流输出:
{
"labels" : [
{
"labelName" : "HR Request Forms"
},
{
"labelName" : "HR Information"
},
{
"labelName" : "Object Low Sensitive"
}
],
"objectName" : "hr-L1-4.xls"
}
我试图仅获取与包含“labelCategory”:“Content”的对象相关的“labelName”(排除称为:“labelCategory”:“Virtual”的对象) . 有什么建议么?谢谢。
答案 0 :(得分:0)
$filter
迭代 labels
的循环并匹配两个条件,它将从 labels
数组返回过滤后的文档$let
声明一个 labels
变量及以上的 $filter
将在标签内,$$labels
中的 in
指的是声明的变量,$$labels.labelName
将返回字符串数组db.getCollection('objects-89aafe20-780f-46ec-aaa0-a2d95bae542e').find({
objectCategory: "Content",
labels: {
$elemMatch: {
labelCategory: "Content",
labelName: { $ne: "Other" }
}
}
},
{
_id: 0,
objectName: 1,
labels: {
$let: {
vars: {
labels: {
$filter: {
input: "$labels",
cond: {
$and: [
{ $eq: ["$$this.labelCategory", "Content"] },
{ $ne: ["$$this.labelName", "Other"] }
]
}
}
}
},
in: "$$labels.labelName"
}
}
})