Aggregate $match help

Hi there,
I have been trying to get this right but unable.
I have the following data in my collection:

{
    "_id": {
        "$oid": "6786a209d6b086487098e54b"
    },
    "date": {
        "$date": "2024-01-02T00:00:00.000Z"
    },
    "hour": 12,
    "numRegistrations": 2,
    "totalValue": 110,
    "company": "1886",
    "partners": [{
        "id": 14,
        "numRegistrations": 1,
        "totalvalue": 90
    }, {
        "id": 7,
        "numRegistrations": 1,
        "totalValue": 20
    }]
}

I am using aggregate to match elements. My difficulty is to write the $match when the “partners” has specific “id”. For example: 14. I want to filter the elements where “partners.id” = 14. The problem is that partners is an array of objects.

My query works well if I don’t add the partners. If I do, it just ignores it and brings back all records for all partners.id:

query= [{“$match”:{“date”:{“$gte”:“2024-01-01T00:00:00.000Z”,“$lte”:“2024-01-03T23:59:59.000Z”},“site”:“1886”,“partners.id”:14}}]

What am I missing? Many thanks.

It would help if you could provide the expected results.

If I try to understand

I think it means that in the sample document you supply you also get the element

and that you only want

If that is the case, I do this in 2 stages. The second stage would be $project, that uses $filter to only keep the appropriate element.

Hi Steeve,
Thanks for answering.
You are right.
The idea of doing in two stages worked.
Sometimes we realize doing everything in one step is not always the way to go.
Cheers mate.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.