12

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 } } }  },
----------------------------------
--------------------------------
]}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Pinaki Mukherjee
  • 1,616
  • 3
  • 20
  • 34
  • 1
    See if this [helps](https://stackoverflow.com/q/7811163) – s7vr Feb 18 '18 at 03:44
  • 2
    You can use `db.companies.find({"$expr":{"$and":[{"$eq":["$founded_year", 2004]}, {"$gte":[{"$size":"$investments"}, 5]}]}})` in 3.6 – s7vr Feb 18 '18 at 06:11

1 Answers1

43

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.

Alejandro Montilla
  • 2,626
  • 3
  • 31
  • 35
  • 7
    It looks like your second option (with `find`) is also working for a $match in an aggregation. Since it looks like dereferencing, I suppose it is pretty fast. Would you still recommend the first method for an aggregation? – bachinblack Feb 10 '19 at 18:45