I Wanted to fetch the document given that we are having the subdocument id .Here lets say we have multiple categories and every category is having subcategory and service type so if i have the subcategory id then how can we fetch the subcategory similarly also if i am having the id of one of service type then how can i fetch the servicetype.
[
{
"_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
Query tried
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;
Expected Output
if i am having the id of any one of the subcategory let 60e95a466f25a34248698a33 then how can i fetch that subcategory if we do not know the category 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"
}
}
]
}
]