使用MongoTemplate和Spring Data MongoDB进行复杂查询

时间:2016-11-14 12:25:05

标签: java mongodb mongodb-query spring-data-mongodb

我正在使用普通的mongodb api,即MongoClient,DB,DBCollection,AggregrationOutput和DBObejct等。我有以下查询工作正常:

MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("myDB");
DBCollection    collection = db.getCollection("my_data");
List<DBObject> pipeline=new ArrayList<DBObject>();              
DBObject match = new BasicDBObject("$match", new BasicDBObject("date", sdf.format(new Date())).append("myName", myName));
DBObject unwind = new BasicDBObject("$unwind", "$myDetails");
DBObject match2 = new BasicDBObject("$match", new BasicDBObject("myDetails.type", "health"));
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("myDetails.datetime", -1));
DBObject limit = new BasicDBObject("$limit", 1);

pipeline.add(match);
pipeline.add(unwind);
pipeline.add(match2);
pipeline.add(sort);
pipeline.add(limit);

AggregationOutput output = collection.aggregate(pipeline);

现在,我想继续使用SpringData mongoDb api。 有人可以帮我用MongoTemplate和MongoOperations写相同的查询吗?

1 个答案:

答案 0 :(得分:1)

以下是我从MongoOperations聚合函数得到的答案:

    ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate"); 

    AggregationOperation match = Aggregation.match(Criteria.where("country").is("India"));
    AggregationOperation unwind = Aggregation.unwind("myDetails");
    AggregationOperation match2 = Aggregation.match(Criteria.where("myDetails.type").is("health"));
    AggregationOperation sort = Aggregation.sort(Sort.Direction.ASC, "myDetails.datetime");
    AggregationOperation limit = Aggregation.limit(1);

    Aggregation aggregation = Aggregation.newAggregation(match, unwind, match2, sort, limit);
    System.out.println("Aggregation = "+aggregation);
    AggregationResults<AggregateFactoryResult> output = mongoOperation.aggregate(aggregation, "gui_data", AggregateFactoryResult.class);
    System.out.println("output = "+output.getMappedResults());