13

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 } } }  },
----------------------------------
--------------------------------
]}
2
  • 1
    See if this helps Commented Feb 18, 2018 at 3:44
  • 2
    You can use db.companies.find({"$expr":{"$and":[{"$eq":["$founded_year", 2004]}, {"$gte":[{"$size":"$investments"}, 5]}]}}) in 3.6 Commented Feb 18, 2018 at 6:11

1 Answer 1

45

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.