직접적인 대답을 얻을 수있는 방법이 없을 것이라고 생각합니다.
aggregate
을 사용하여 구현할 수 있습니다. 특정 문서에 배열 brand
의 요소 수를 얻을하려는 경우 예를 들어,이 방법은 (몽고 쉘에서 실행) 가능해야한다 :
db.Award.aggregate({$match:{_id:id}}, {$unwind:"$brand"}, {$group:{_id:"$_id", count:{$sum:1}}});
count
당신이 원하는 결과입니다.
그런 다음 spring-data-mongodb 구문을 사용하여 구현하십시오.
-------------- 추가 ---------------------
// You can find the relative aggregation method from MongoTemplate.java file to handle your requirements.
// For exmaple:
// public <O> AggregationResults<O> aggregate(Aggregation aggregation, Class<?> inputType, Class<O> outputType)
// The version is around spring-data-mongodb-1.5.0 or higher.
// Below I call the mongo-java-driver directly because I find it needs some time to learn it from spring-data-mongodb. :)
protected int getArraySize(Object id, String collName) {
// Attention: make sure id is in the correct data type because the following statement would not convert it automatically.
// Issue codes according to this command line:
// db.Award.aggregate({$match:{_id:id}}, {$unwind:"$brand"}, {$group:{_id:"$_id", count:{$sum:1}}});
DBObject match = BasicDBObjectBuilder.start().push("$match").append("_id", id).get();
DBObject unwind = new BasicDBObject("$unwind", "$brand");
DBObject group = BasicDBObjectBuilder.start().push("$group").append("_id", "$_id").push("count").append("$sum", 1).get();
List<DBObject> pipeline = Arrays.asList(match, unwind, group);
// This aggregate method is supported in higher version of mongo-java-driver, here I use is 2.12.3
AggregationOutput aggr = this.mongoTemplate.getCollection(collName).aggregate(pipeline);
for (DBObject dbo : aggr.results()) {
Object count = dbo.get("count");
if (count instanceof Number) {
return ((Number)count).intValue();
}
}
return 0;
}
이 작품 MongoDB Console에서. 그러나 스프링 데이터를 사용하여 비슷한 메커니즘을 사용할 수 있다고 제안 할 수 있습니까? findOne을 사용하여 문서를 Java 객체로 가져온 다음 list.size()를 수행하여 배열 수를 얻습니다. 나는 그것의 예쁜 방법이 아니라는 것을 안다! – Karthik
@ Karthik, 결과에 상대적인 방법을 추가했습니다. 아마도 도움이 될 것입니다. – Wizard