首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较对象数组中数组的大小

比较对象数组中数组的大小
EN

Stack Overflow用户
提问于 2017-09-10 09:41:22
回答 1查看 90关注 0票数 0

我想find所有sCompetitions.length大于competitions.length的文档。

以下是一些示例文档文档:

代码语言:javascript
复制
{
    "_id" : ObjectId("59b28f432b4353d3f311dd1b"),
    "name" : "Ford Focus RS 2008",
    "requirements" : [ 
        {
            "rankType" : "D1",
            "competitions" : [ 
                ObjectId("59b151fd2b4353d3f3116827"), 
                ObjectId("59b151fd2b4353d3f3116829")
            ],
            "sCompetitions" : [ 
                "Rallye Monte-Carlo", 
                "Rally Sweden"
            ]
        }, 
        {
            "rankType" : "A3",
            "competitions" : [
                ObjectId("59b151fd2b4353d3f3116f6b")
            ],
            "sCompetitions" : [ 
                "Rally Italia Sardegna", 
                "Neste Rally Finland"
            ]
        }
    ]
},
{
    "_id" : ObjectId("0000b28f432b4353f311dd1b"),
    "name" : "Ford Focus RS 2012",
    "requirements" : [ 
        {
            "rankType" : "D1",
            "competitions" : [ 
                ObjectId("59b151fd2b4353d3f3116827"), 
                ObjectId("59b151fd2b4353d3f3116829")
            ],
            "sCompetitions" : [ 
                "Rallye Monte-Carlo", 
                "Rally Sweden"
            ]
        }, 
        {
            "rankType" : "A3",
            "competitions" : [
                ObjectId("59b151fd2b4353d3f3116f6b"),
                ObjectId("59b151fd2b4353d3f3116f6b")
            ],
            "sCompetitions" : [ 
                "Rally Italia Sardegna", 
                "Neste Rally Finland"
            ]
        }
    ]
}

所以看一下样本,它只会返回ObjectId("59b28f432b4353d3f311dd1b")

我的问题是requirements本身就是一个数组,所以我需要以某种方式迭代它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-10 09:48:18

不需要“迭代”。您真正需要的是在从$anyElementTrue返回结果之后进行$map检查。您可以在$redact操作中完成所有这些操作:

代码语言:javascript
复制
Model.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$anyElementTrue": {
          "$map": {
            "input": "$requirements",
            "as": "r",
            "in": { 
              "$gt": [
                { "$size": "$$r.sCompetitions" },
                { "$size": "$$r.competitions" }
              ]
            }
          }
        }
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

因此,这是$size对每个数组元素的简单比较,如果其中“任何”元素是true,则文档将从结果中“保存”或“修剪”。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46139292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档