Je ne pense pas qu'il existe une méthode qui puisse obtenir la réponse directement. Vous pouvez utiliser le aggregate
pour l'implémenter. Par exemple, si vous voulez obtenir le nombre d'éléments dans le tableau brand
dans un document spécifique, de cette façon devrait être disponible (courir sur shell mongo):
db.Award.aggregate({$match:{_id:id}}, {$unwind:"$brand"}, {$group:{_id:"$_id", count:{$sum:1}}});
count
est le résultat que vous voulez. Ensuite, implémentez cette méthode en utilisant la syntaxe spring-data-mongodb.
-------------- --------------------- ANNEXES
// 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;
}
Cela fonctionne depuis la console MongoDB. Mais pouvez-vous suggérer si nous avons le même mécanisme possible en utilisant Spring Data? Utilisation de findOne J'ai pris le document en tant qu'objet dans Java, puis j'ai exécuté listSize() pour obtenir le nombre de tableaux. Je sais que ce n'est pas une belle façon de faire! – Karthik
@Karthik, j'ai ajouté la méthode relative au résultat. Cela aidera peut-être. – Wizard