|
| 1 | +package myconext.repository; |
| 2 | + |
| 3 | +import com.mongodb.client.AggregateIterable; |
| 4 | +import myconext.model.User; |
| 5 | +import org.springframework.beans.factory.annotation.Autowired; |
| 6 | +import org.springframework.data.mongodb.core.MongoTemplate; |
| 7 | +import org.springframework.data.mongodb.core.aggregation.*; |
| 8 | +import org.bson.Document; |
| 9 | +import org.springframework.stereotype.Repository; |
| 10 | + |
| 11 | +import java.util.Arrays; |
| 12 | +import java.util.List; |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | +@Repository |
| 16 | +public class MetricsRepository { |
| 17 | + |
| 18 | + private final MongoTemplate mongoTemplate; |
| 19 | + |
| 20 | + public MetricsRepository(MongoTemplate mongoTemplate) { |
| 21 | + this.mongoTemplate = mongoTemplate; |
| 22 | + } |
| 23 | + |
| 24 | + public Number getTotalLinkedAccountCount() { |
| 25 | + UnwindOperation unwindLinkedAccounts = Aggregation.unwind("linkedAccounts"); |
| 26 | + CountOperation countTotal = Aggregation.count().as("totalLinkedAccounts"); |
| 27 | + TypedAggregation<User> aggregation = Aggregation.newAggregation( |
| 28 | + User.class, |
| 29 | + unwindLinkedAccounts, |
| 30 | + countTotal |
| 31 | + ); |
| 32 | + AggregationResults<Map> results = mongoTemplate.aggregate( |
| 33 | + aggregation, |
| 34 | + Map.class |
| 35 | + ); |
| 36 | + return (Number) results.getUniqueMappedResult().get("totalLinkedAccounts"); |
| 37 | + } |
| 38 | + |
| 39 | + // Alternative approach: Using MongoTemplate's native execute method |
| 40 | + public Number countTotalLinkedAccountsNativeExecute() { |
| 41 | + /* |
| 42 | + users.aggregate([ |
| 43 | + { |
| 44 | + "$unwind": "$linkedAccounts" |
| 45 | + }, |
| 46 | + { |
| 47 | + "$count": "totalLinkedAccounts" |
| 48 | + } |
| 49 | + ]) |
| 50 | +
|
| 51 | + */ |
| 52 | + return mongoTemplate.execute("users", collection -> { |
| 53 | + List<Document> pipeline = Arrays.asList( |
| 54 | + Document.parse("{ \"$unwind\": \"$linkedAccounts\" }"), |
| 55 | + Document.parse("{ \"$count\": \"totalLinkedAccounts\" }") |
| 56 | + ); |
| 57 | + |
| 58 | + AggregateIterable<Document> result = collection.aggregate(pipeline); |
| 59 | + Document doc = result.first(); |
| 60 | + |
| 61 | + return doc != null ? doc.getInteger("totalLinkedAccounts") : 0; |
| 62 | + }); |
| 63 | + } |
| 64 | +} |
0 commit comments