I'm currently having some problems with the usage of java, aggregations and the mongodb.
I have 2 collections in a mongodb.
example collection: person
{
id: 1
name: "Oliver"
companyId: 5
}
example collection: company
{
id: 5
name: asdf
}
Now I want to join those collections by companyId/id (lookup aggregation?) and want to iterate over the result. I dont want to load the whole resultset in to the memory, rather iterate 1 by 1. I think i need some kind of cursor (mongoCursor?).
Im working with Java and Spring. So I have the possibilities to use the Java Mongo Driver (version: 3.7.1) or the Options which provides the Springframework (version 5.0.6).
edit:
In the following example Cursor.hasNext() is always false.
DBObject match = new BasicDBObject("$match",
new BasicDBObject("companyId", "id"));
DBObject lookupFields = new BasicDBObject("from", "company");
lookupFields.put("localField", "companyId");
lookupFields.put("foreignField", "id");
lookupFields.put("as", "personWithCompany");
DBObject lookup = new BasicDBObject("$lookup", lookupFields);
DBObject projectFields = new BasicDBObject("id", 1);
projectFields.put("name", 1);
projectFields.put("companyName", "$company.name);
List<DBObject> pipeline = Arrays.asList(match, lookup, project);
Cursor cursor = mongoTemplate.getCollection("person").aggregate(pipeline, AggregationOptions.builder().allowDiskUse(true).build());
while (cursor.hasNext()) {
DBObject dbObject = cursor.next();
}
person.aggregate([
"$lookup": {
"from": "company",
"localField": "companyId",
"foreignField": "id",
"as": "PersonDetails"
},
{$unwind: "$PersonDetails"}
]);
joining with Person Collection with company
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.