2

I have this documents

[

    {
        "id" : 1,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 12
                    }
                ]
            },
            {
                "value": 100,
                "term": [
                    {
                        "term_value" : 18
                    }
                ]
            }
        ]
    },
    {
        "id" : 2,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 18
                    }
                ]
            },
            {
                "value": 150,
                "term": [
                    {
                        "term_value" : 24
                    }
                ]
            }
        ]
    }
]

i want to use aggregation framework to get documents that have at least one prices.term.value equals 6

I am using this

Product.aggregate(
    [
        { "$match": { "prices.term.value": {"$eq": 6} } },
    ]
)

it returns all documents because all have at least one term satisfy the condition, and no problem

what I need is, using $filter to just return prices that have at least one term satisfies the condition

this a dumy code of what i need

{
    "$addFields": {
        "prices": {
            "$filter": {
                "input": "$prices",
                "as": "field0",
                "cond": {
                    "$eq": [
                        "$$field0.term.term_value",
                        6
                    ]
                }
            }
        }
    }
}

but its nor working, any advice ?

my needed result is

[

    {
        "id" : 1,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 12
                    }
                ]
            },
        ]
    },
    {
        "id" : 2,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 18
                    }
                ]
            },
        ]
    }
]

Thanks

Moustafa Elkady
  • 670
  • 1
  • 7
  • 17

0 Answers0