как запросить mongodb с помощью java
Sep 04 2020
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" }}}])
Как запросить вышеуказанный запрос в java, я попытался использовать приведенный ниже код
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));
но я становлюсь пустым на выходе. Вышеупомянутый запрос дает точный результат, который я хочу при запуске в cmd.
Ответы
1 KayV Sep 04 2020 at 15:04
Вы можете использовать класс AggregationOperation, как указано в этой ссылке
Что-то вроде этого:
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());
}
LauraLiparulo Sep 04 2020 at 15:38
вы можете написать приложение для весенней загрузки с данными Spring https://spring.io/guides/gs/accessing-data-mongodb/