In my mongodb document, I have array inside array & I want to put filter on it in projection.
Sample Document:
{
"_id" : ObjectId("5a3ba402cc96937e91e2861d"),
"id" : 1,
"name" : "a",
"var" : [
{
"id" : 11,
"name" : "aa",
"data" : [
{
"type" : 1,
"value" : "A"
},
{
"type" : 2,
"value" : "B"
}
]
},
{
"id" : 12,
"name" : "ab",
"data" : [
{
"type" : 26,
"value" : "Z"
},
{
"type" : 10,
"value" : "J"
}
]
}
]
}
When I run following query,
db.harshit.aggregate([{
$match: { "id" : 1}
}, {
$project: {
"_id" : 1,
"id" : 1,
"name" : 1,
"var" : {
$filter: {
input: "$var",
as: "var1",
cond: {
"$eq": ["$$var1.id", 12]
}
}
}
}
}
])
then it gives expected result
{
"_id" : ObjectId("5a3ba402cc96937e91e2861d"),
"id" : 1,
"name" : "a"
"var" : [
{
"id" : 12,
"name" : "ab",
"data" : [
{
"type" : 26,
"value" : "Z"
},
{
"type" : 10,
"value" : "J"
}
]
}
]
}
but if I use following query
db.harshit.aggregate([{
$match: { "id" : 1}
}, {
$project: {
"_id" : 1,
"id" : 1,
"name" : 1,
"var" : {
$filter: {
input: "$var",
as: "var1",
cond: {
"$eq": ["$$var1.data.type", 26]
}
}
}
}
}
])
then it gives empty array for "var"
{
"_id" : ObjectId("5a3ba402cc96937e91e2861d"),
"id" : 1,
"name" : "a"
"var" : []
}
I want to put filter on nested array "var.data" and want to project the objects that match the condition.
How do I filter those nested arrays?