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

时间:2017-09-10 09:41:22

标签: mongodb mongoose mongodb-query aggregation-framework

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

这里有一些示例文档文档:

{
    "_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本身就是一个数组,所以我需要以某种方式迭代它

1 个答案:

答案 0 :(得分:1)

无需"迭代"。从$anyElementTrue返回结果后,您真正需要的是$map检查。您可以在$redact操作中执行此操作:

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

所以它是$size对每个数组元素的简单比较,然后是" any"这些元素是true,文件是"保留"或以其他方式"修剪"从结果。