如果有以下數(shù)據(jù)狱杰,我們想獲取數(shù)字字段arrayfield的長度屹耐,該怎么辦呢?
{
"_id" : "test_id",
"array_field" : [
"value1",
"value2",
"value3"
]
}
雖然我們可以直接查詢該字段的內(nèi)容然后獲取其長度臼膏,但是當(dāng)數(shù)據(jù)量大時性能就很差了硼被。這里我們用聚合函數(shù)來獲取。
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();
以上是查詢單條記錄的數(shù)組字段長度渗磅。如果我們要批量查詢所有記錄的數(shù)組字段長度的列表呢嚷硫?我們可以想當(dāng)然的認為只要將$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();