I have the following BSON data:
[
{
"test": 1,
"arr": [
{
age: 24,
name: "a"
},
{
age: 55,
name: "b"
},
{
age: 12,
name: "c"
},
{
age: 14,
name: "d"
},
{
age: 67,
name: "e"
}
]
}
]
Is it possible by using only "find" method I get the output in a way that the "age" field inside "arr" array is less than 30 for each array element?.
So My expected output:
[
{
"test": 1,
"arr": [
{
age: 24,
name: "a"
}
{
age: 12,
name: "c"
},
{
age: 14,
name: "d"
}
]
}
]
If also it is possible with one find to flatten the array that would be great too.
Explained in the above.
>Solution :
You can use the $filter operator to filter the element(s) in an array in the projection.
db.collection.find({
"arr.age": {
$lt: 30
}
},
{
"test": 1,
"arr": {
$filter: {
input: "$arr",
cond: {
$lt: [
"$$this.age",
30
]
}
}
}
})