我想提取文档,因为我们有子文档id。这里假设我们有多个类别,每个类别都有子类别和服务类型,所以如果我有子类别id,那么我们如何类似地提取子类别?如果我有某个服务类型的id,那么我如何提取服务类型。
[
{
"_id": {
"$oid": "60e958b8f907544930c7d045"
},
"trans": {
"en": {
"name": "Digital Marketing",
"description": "Digital Marketing"
},
"fr": {
"name": "Digital Marketing",
"description": "Digital Marketing"
}
},
"subcategories": [
{
"trans": {
"en": {
"name": "Social Media Advertising",
"description": "Social Media Advertising"
}
},
"$oid": "60e95a466f25a34248698a33",
"service_type": [
{
"trans": {
"en": {
"name": "_service1",
"description": "_service1"
}
},
"_id": {
"$oid": "60e95a466f25a34248698a30"
}
},
{
"trans": {
"en": {
"name": "Strategy and Planning",
"description": "Strategy and Planning"
}
},
"_id": {
"$oid": "60e95a466f25a34248698a31"
}
},
{
"trans": {
"en": {
"name": "AD SETUP AND MANAGEMENT",
"description": "AD SETUP AND MANAGEMENT"
}
},
"_id": {
"$oid": "60e95a466f25a34248698a32"
}
}
]
},
{
"trans": {
"en": {
"name": "Social Media Marketing",
"description": "Social Media Marketing"
}
},
"$oid": "60e95a466f25a34248698a33",
"service_type": [
{
"trans": {
"en": {
"name": "_serviceA",
"description": "_serviceA"
}
},
"_id": {
"$oid": "60e95a466f25a34248678a78"
}
},
{
"trans": {
"en": {
"name": "Strategy 1",
"description": "Strategy 1"
}
},
"_id": {
"$oid": "60e95a466f25a34248222a31"
}
},
{
"trans": {
"en": {
"name": "AD 2",
"description": "AD 2"
}
},
"_id": {
"$oid": "51e85a466f25a34345498a32"
}
}
]
}
]
}
]
//similarly we are having multiple categories then how can we fetch the subcategory with given `subcategory_id` where the subcategory is an array of object
已尝试查询
const r = await client
.collection("categories")
.aggregate([
{
$project: {
categories: 0,
subcategories: {
$filter: {
input: "$subcategories",
as: "subcategory",
cond: {
if: {
$eq: ["$$subcategory._id", "60e51a116678530e84ee2e86"],
},
then: "$$subcategory",
else: "not found",
},
},
},
},
},
])
.toArray();
console.log("answer", r);
return r;
预期输出
如果我有任何一个子类别的id let60e95a466f25a34248698a33
,那么如果我们不知道类别id,我如何获取该子类别?
"subcategories":[
{
"trans": {
"en": {
"name": "Social Media Advertising",
"description": "Social Media Advertising"
}
},
"$oid": "60e95a466f25a34248698a33",
"service_type": [
{
"trans": {
"en": {
"name": "_service1",
"description": "_service1"
}
},
"_id": {
"$oid": "60e95a466f25a34248698a30"
}
},
{
"trans": {
"en": {
"name": "Strategy and Planning",
"description": "Strategy and Planning"
}
},
"_id": {
"$oid": "60e95a466f25a34248698a31"
}
},
{
"trans": {
"en": {
"name": "AD SETUP AND MANAGEMENT",
"description": "AD SETUP AND MANAGEMENT"
}
},
"_id": {
"$oid": "60e95a466f25a34248698a32"
}
}
]
}
]
该查询有两个问题:
- 除了在包含投影中排除
_id
之外,不能在同一投影中同时包含和排除字段 $filter
内部的cond
表达式应计算为布尔值
$eq
运算符本身的计算结果为布尔值,因此不需要额外的if
。
要只返回子类别字段,而不返回_id
或任何类别字段,请使用:
.aggregate([
{
$project: {
_id: 0,
subcategories: {
$filter: {
input: "$subcategories",
as: "subcategory",
cond: {
$eq: ["$$subcategory._id", "60e51a116678530e84ee2e86"],
},
},
},
},
},
])