【问题标题】:Mongo DB aggregation array size greater than match [duplicate]Mongodb聚合数组大小大于匹配[重复]
【发布时间】:2018-07-28 14:29:48
【问题描述】:

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

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

我在下面写的匹配查询不起作用。任何建议:

db.companies.aggregate( [
    { $match:  {"founded_year" : 2004}, 
  {  "investments" : {$size: : { $gte: 5 } } }  },
----------------------------------
--------------------------------
]}

【问题讨论】:

  • 看看这个helps
  • 你可以在3.6中使用db.companies.find({"$expr":{"$and":[{"$eq":["$founded_year", 2004]}, {"$gte":[{"$size":"$investments"}, 5]}]}})

标签: mongodb aggregation-framework


【解决方案1】:

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 的那些。

find:

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

你问investments数组中的位置号6是否存在。

【讨论】:

  • 看起来你的第二个选项(find)也适用于聚合中的 $match。由于它看起来像取消引用,我想它非常快。你还会推荐第一种聚合方法吗?
猜你喜欢
  • 1970-01-01
  • 2013-01-12
  • 2020-09-11
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 2012-08-31
相关资源
最近更新 更多