MongoDB : $size 的参数必须是数组,但类型为:缺失

MongoDB : The argument to $size must be an array, but was of type: missing

它抛出错误:org.springframework.dao.InvalidDataAccessApiUsageException:命令执行失败:错误[$size 的参数必须是一个数组,但类型为:缺失]

我必须从中找到特定调查、问题、选项 ID 的用户 ID 计数的 mongo 文档

{
    "_id" : ObjectId("5ea31dce0e4d4b09e4db0cd6"),
    "_class" : "com.litmus7.river.commons.common.model.survey.Result",
    "survey_id" : "5ea30df40e4d4b4de4d7b6d7",
    "survey_question" : [ 
        {
            "question_id" : "5ea30df40e4d4b4de4d7b6d2",
            "question_options" : [ 
                {
                    "option_id" : "5ea30df40e4d4b4de4d7b6d1",
                    "user_id" : [ 
                        "111", 
                        "222"
                    ]
                }, 
                {
                    "option_id" : "5ea30df40e4d4b4de4d7b6cf",
                    "user_id" : [ 
                        "333", 
                        "444"
                    ]
                }
            ]
        }, 
        {
            "question_id" : "5ea30df40e4d4b4de4d7b6d6",
            "question_options" : [ 
                {
                    "option_id" : "5ea30df40e4d4b4de4d7b6d3",
                    "user_id" : [ 
                        "111", 
                        "222"
                    ]
                }, 
                {
                    "option_id" : "5ea30df40e4d4b4de4d7b6d5",
                    "user_id" : [ 
                        "333", 
                        "444"
                    ]
                }
            ]
        }
    ]
}

** 聚合函数编写:**

public int getResultCount() {
        Aggregation aggregation = newAggregation(
            match(Criteria.where("survey_id").is("5ea30df40e4d4b4de4d7b6d7")),
            unwind("survey_question"),
            match(Criteria.where("survey_question.question_id").is("5ea30df40e4d4b4de4d7b6d2")),
            unwind("survey_question.question_options"),
            match(Criteria.where("survey_question.question_options.option_id").is("5ea30df40e4d4b4de4d7b6d1")),
            project()
                .and("survey_question.question_options.user_id")
                .size()
                .as("count"));

        AggregationResults<Object> results = mongoTemplate.aggregate(aggregation, "result", Object.class);
        if (results != null && results.getMappedResults() != null && results.getMappedResults().size() > 0) {
            Integer intCount = (Integer) ((Map) results.getMappedResults().get(0)).get("count");
            return intCount;
        }
        return 0;
    }

您需要使用$ifNull运算符:

.project().and(ArrayOperators.arrayOf(ConditionalOperators
    .ifNull("survey_question.question_options.user_id").then(Collections.emptyList())).length())
.as("count");