Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm trying to filter the list of an array of array arrays, this is an example of structure.
"array1": [
"array2": [
"array3": [
"sampleId": 1
"sampleId": 2
"sampleId": 5
"array3": [
"sampleId": 7
"sampleId": 8
"array2": [
"array3": [
"sampleId": 1
Let's say that i want to filter out all the subdocuments with sampleId > 2
this is an example of the expected result.
"array1": [
"array2": [
"array3": [
"sampleId": 1
"sampleId": 2
"array3": []
"array2": [
"array3": [
"sampleId": 1
I tried using aggregation/map/filter technique as explained in
this post
and others but the results are always giving array3 empty.
You can try below aggregation
Basically you need to loop over each array using
$map
aggregation and finally use
$filter
with the last one.
db.collection.aggregate([
{ "$project": {
"array1": {
"$map": {
"input": "$array1",
"as": "a1",
"in": {
"array2": {
"$map": {
"input": "$$a1.array2",
"as": "a2",
"in": {
"array3": {
"$filter": {
"input": "$$a2.array3",
"as": "a3",
"cond": { "$lte": ["$$a3.sampleId", 2] }
Output
"array1": [
"array2": [
"array3": [
"sampleId": 1
"sampleId": 2
"array3": []
"array2": [
"array3": [
"sampleId": 1
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.