Mongo DB aggregation array size greater than match [duplicate]

一曲冷凌霜 提交于 2020-11-30 12:37:30

问题


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 } } }  },
----------------------------------
--------------------------------
]}

回答1:


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.



来源:https://stackoverflow.com/questions/48847800/mongo-db-aggregation-array-size-greater-than-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!