Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB aggregation array size greater than match [duplicate]

I have a collection where investments is an array inside the mongodb document. Now using aggregation I am trying to filter results where investments length is more than 5 times and then do the next processing using match query.

 Collection{
 _id:000000
 --------------------- 
 "investments" : [      {
          hhhhhhhhhhhhhh 
         },
         {
           hhhhhhhhhhhhhh 
          } }]
-----------------

The match query I wrote like below which isn't working. Any suggestions:

db.companies.aggregate( [
    { $match:  {"founded_year" : 2004}, 
  {  "investments" : {$size: : { $gte: 5 } } }  },
----------------------------------
--------------------------------
]}
like image 828
Pinaki Mukherjee Avatar asked Feb 18 '18 02:02

Pinaki Mukherjee


1 Answers

With aggregate:

db.companies.aggregate([
  { $match:  { "founded_year":2004 } },
  { $project: { founded_year:1,  
                moreThanFive: { $gt: [ {$size: "$external_links" }, 5 ] } } },
  { $match: { moreThanFive : true }} ,
])

You will need to:
1. Include a $project stage, to find the number of investement (the size of the array), and check if that greater than 5.
2. and then do another $match stage to filter those with moreThanFive equals to true.

With find:

db.companies.find({'investments.5': {$exists: true}})

You ask if the position number 6 in the investments array exists.

like image 142
Alejandro Montilla Avatar answered Sep 28 '22 01:09

Alejandro Montilla