如果有以下数据,我们想获取数字字段arrayfield的长度,该怎么办呢?
{
"_id" : "test_id",
"array_field" : [
"value1",
"value2",
"value3"
]
}
虽然我们可以直接查询该字段的内容然后获取其长度,但是当数据量大时性能就很差了。这里我们用聚合函数来获取。
Shell
db.test_collection.aggregate([{ "$match" : { "_id" : "test_id"}}, { "$project" : {"cnt":{"$size":"$array_field"} }} ])
Java
List<AggregationOperation> ops = new ArrayList<>();
ops.add(Aggregation.match(Criteria.where("_id").is("test_id")));
ops.add(Aggregation.project().and("array_field").size().as("cnt"));
List<Map> results = mongoTemplate.aggregate(Aggregation.newAggregation(ops), "test_collection", Map.class).getMappedResults();
以上是查询单条记录的数组字段长度。如果我们要批量查询所有记录的数组字段长度的列表呢?我们可以想当然的认为只要将$match修改一下就行了。但是很不幸,这样有很大的概率会报这样的错误信息
The argument to $size must be an Array, but was of type: EOO
这种情况其实很好解决,加上 ifNull 就行了
Shell
db.test_collection.aggregate([ { "$project" : { "cnt": { "$size": { "$ifNull": [ "$array_field", [] ] } } } } ])
Java
List<AggregationOperation> ops = new ArrayList<>();
ops.add(Aggregation.match(Criteria.where("_id").is("test_id")));
ops.add(Aggregation.project().and(ArrayOperators.Size.lengthOfArray(ConditionalOperators.ifNull("array_field").then(Collections.emptyList()))).as("cnt"));
List<Map> results = mongoTemplate.aggregate(Aggregation.newAggregation(ops), "test_collection", Map.class).getMappedResults();