node.js - Query for documents where dependent array size matches a value -


i have following schema:

collection1   name   slug collection2   name   slugcollection1 

the "link" between collection1 , collection2 through fields slug , slugcollection1.

i try implement request aggregation framework of mongodb elements of collection1 have specific name , number of dependent elements of type collection2.

i can 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 can't use elementsnumber field $match later. guess it's because it's not field part of collection1.

is there way implement such query? thanks!

you can of course use $match pipeline filter documents 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

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -