Mongo DB聚合数组大小大于匹配项 [英] Mongo DB aggregation array size greater than match

查看:72
本文介绍了Mongo DB聚合数组大小大于匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,其中投资是mongodb文档中的一个数组.现在使用聚合,我试图过滤投资长度大于5倍的结果,然后使用匹配查询进行下一个处理.

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

推荐答案

带有 aggregate :

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

您将需要:
1.包括一个 $ project 阶段,以查找投资数量(​​数组的 size ),并检查其是否大于5.
2.然后执行另一个 $ 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.

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

您询问在 investments 数组中的排名6是否存在.

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

这篇关于Mongo DB聚合数组大小大于匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆