1 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個(gè)贊
您不必多次調(diào)用數(shù)據(jù)庫(kù),$lookup將完全按照您在聚合框架中的要求進(jìn)行操作。
嘗試以下查詢:
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());
}
添加回答
舉報(bào)