1 回答
TA贡献1806条经验 获得超5个赞
您不必多次调用数据库,$lookup将完全按照您在聚合框架中的要求进行操作。
尝试以下查询:
db.getCollection("employee_leads").aggregate([
{
$match : {
"_id" : new ObjectId("5d55ac30e533bc76e4581923") // This is in case you want to filter anything.
}
},
{
$lookup : {
"from": "employee",
"localField": "leads",
"foreignField": "_id",
"as": "leads"
}
}])
上述查询的 Java 等效代码:
示例 1
List<Bson> aggregates = Arrays.asList(
Aggregates.match(Filters.eq("_id", new ObjectId("5d55ac30e533bc76e4581923"))),
Aggregates.lookup("employee", "leads", "_id", "leads"));
AggregateIterable<Document> iterable = this.collection.aggregate(aggregates);
示例 2
List<Document> aggregates = Arrays.asList(
new Document("$match", new Document("_id", new ObjectId("5d55ac30e533bc76e4581923"))),
new Document("$lookup", new Document("from", "employee")
.append("localField", "leads")
.append("foreignField", "_id")
.append("as", "leads")));
AggregateIterable<Document> iterable = collection.aggregate(aggregates);
for (Document row : iterable) {
System.out.println(row.toJson());
}
添加回答
举报