Thierry Templier Thierry Templier - 20 days ago 8
Node.js Question

Query for documents where dependent array size matches a value

I have the following schema:

Collection1
name
slug
Collection2
name
slugCollection1


The "link" between
Collection1
and
Collection2
is through fields
slug
and
slugCollection1
.

I try to implement a request with the aggregation framework of MongoDB to get all elements of
Collection1
that have a specific name and number of dependent elements of type
Collection2
.

I can get the hints leveraging
$project
:

[
{
"$lookup": {
"from": "Collection2",
"localField": "slug",
"foreignField": "slugCollection1",
"as": "elements"
}
},
{
"$project": {
"_id": 0,
"id": "$id",
"name": 1,
"slug": 1,
"elementsNumber": {
"$size": "$elements"
}
}
}
]


But I can't use the
elementsNumber
field into
$match
later. I guess that it's because it's not a field part of the
Collection1
.

Is there a way to implement such query?
Thanks!

Answer

You can of course use a $match pipeline to filter the documents with the given criteria as:

[
    {
        "$lookup": {
            "from": "Collection2",
            "localField": "slug",
            "foreignField": "slugCollection1",
            "as": "elements"
        }
    },
    {
        "$project": {
            "_id": 0,
            "id": "$id",
            "name": 1,
            "slug": 1,
            "elementsNumber": { "$size": "$elements" }
        }
    },
    { "$match": { "elementsNumber": { "$gt": 3 } } }
]
Comments