简体   繁体   中英

how to query mongodb using java

 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.

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());
}

您可能会使用 spring-data https://spring.io/guides/gs/accessing-data-mongodb/编写一个 spring boot 应用程序

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM