Reputation: 21
db.FNTeams.aggregate([ { "$unwind": "$mailIDs" },{ "$lookup": {"from":
"FNContacts", "localField": "mailIDs", "foreignField": "_id", "as":
"productObjects" }}, { "$group": { "_id": "$_id", "mailIDs": { "$push":
"$mailIDs" }, "UserID":{"$push":"$UserID"},"TeamName":
{"$push":"$TeamName"},"productObjects": { "$push": "$productObjects" }}}])
How to query the above query in java, I have tried using below code
DBCollection collection = db.getCollection("FNActivity");
DBObject unwind1 = new BasicDBObject("$unwind", "$mailIDs");
DBObject lookup = new BasicDBObject("$lookup", new BasicDBObject("from",
"FNContacts")
.append("localField", "mailIDs").append("foreignField",
"_id").append("as", "mailWithID"));
BasicDBObject pushField = new BasicDBObject();
pushField.append("_id", "$_id");
pushField.append("UserID", new BasicDBObject("$push", "$UserID"));
pushField.append("TeamName", new BasicDBObject("$push", "$TeamName"));
pushField.append("TeamDesc", new BasicDBObject("$push", "$TeamDesc"));
pushField.append("Status", new BasicDBObject("$push", "$Status"));
pushField.append("MailWithID", new BasicDBObject("$push",
"$mailWithID"));
DBObject group = new BasicDBObject("$group", pushField);
AggregationOutput output = collection.aggregate(Arrays.asList(group,
lookup, unwind1));
but I'm getting empty in output. The above query gives the exact output what I want while run in cmd.
Upvotes: 2
Views: 56
Reputation: 2897
you might write a spring boot application with spring-data https://spring.io/guides/gs/accessing-data-mongodb/
Upvotes: 0
Reputation: 13835
You can use AggregationOperation class, as specified in this link
Something like this:
public static void checkMongoOperations(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
AggregationOperation match = Aggregation.match(Criteria.where("country").is("tiro"));
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().get(0).getCountry());
}
Upvotes: 1