{
"id":"",
"data0":"",
"data1":[
{
"data2":[
{
"name":"Man 1",
"_id":"5e8c242f751d0074ca004a"
},
{
"name":"Man 2",
"_id":"605d403dab6100e1395697"
},
{
"name":"Man 3",
"_id":"5e8c2d39751d0074ca0050"
}
]
},
{
"data2":[
{
"name":"Man 4",
"_id":"5ed4efc71224005abea7eb"
},
{
"name":"Man 5",
"_id":"5e8c249539751d04ca0056"
},
{
"name":"Man 6",
"_id":"5e8c239a39751d0074c046"
}
]
}
]
}
The document above is the structure of my data. Is there a way i can filter the element of an array (data1) where name is Man 3. I want to show only the array element where the value of name is Man 3. I have this code but it is not working. heres the sample.
pipeLine.push(
{ $project: {
'data1' : {
$filter: {
input: '$data1.data2',
as: 'test',
cond: { $eq : ['$$test.name', "Man 3" ]}
}
}
}}
)
Expected output is this.
{
"id":"",
"data0":"",
"data1":[
{
"data2":[
{
"name":"Man 1",
"_id":"5e8c242f751d0074ca004a"
},
{
"name":"Man 2",
"_id":"605d403dab6100e1395697"
},
{
"name":"Man 3",
"_id":"5e8c2d39751d0074ca0050"
}
]
}
]
}
CodePudding user response:
You should use $in operator to check whether "Man 3" is in data1.data2.name, which this path will return the name array.
db.collection.aggregate([
{
$project: {
"data1": {
$filter: {
input: "$data1",
cond: {
$in: [
"Man 3",
"$$this.data2.name"
]
}
}
}
}
}
])
CodePudding user response:
If you only want that filter you can use a find query instead of an aggregation:
db.collection.find({
"data1.data2.name": "Man 3"
},
{
"id": 1,
"data0": 1,
"data1.data2.$": 1
})
Example here
Also if you want an aggregation stage use $in instead of $eq:
db.collection.aggregate([
{
"$project": {
"id": 1,
"data0": 1,
"data1": {
"$filter": {
"input": "$data1",
"as": "d",
"cond": {
"$in": [
"Man 3",
"$$d.data2.name"
]
}
}
}
}
}
])
Example here
